Skip to main content

Apache Slash-y

gahhhhhh this was driving me crazy, putting it here so i don't lose it

basically this solves the problem where you have pages like

http://example.com/page2/index.php?query=true

and you want it to display in the browser as the much nicer

http://example.com/page2?query=true

and you can't use nginx try_files because you promised yourself you were gonna make this work in apache "for old times' sake"

basically: this takes a surprisingly large number of rewrite rules. in order:

RewriteEngine On
#LogLevel alert rewrite:trace6

# remove trailing slash
RewriteRule (\/.*)\/+(\?.*)?$ $1$2 [R]

# remove file extensions
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f
RewriteRule (.*)\.(php|html)(\?.*)?$ $1$3 [NC,R]

# remove index.php index.html etc
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule (.*)\/index(\?.*)?$ $1$2 [NC,R]

# serve php file
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule (\?.*)?$ fcgi://php:9000/usr/local/apache2/htdocs/%{REQUEST_URI}.php$1 [P,L]

# serve php file with index
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}/ -d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}/index.php -f
RewriteRule (\?.*)?$ fcgi://php:9000/usr/local/apache2/htdocs/%{REQUEST_URI}/index.php$1 [P,L]

# serve html file
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.html -f
RewriteRule ([^?]*)(\?.*)?$ $1.html$2 [L]

# serve html file with index
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}/ -d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}/index.html -f
RewriteRule ([^?]*)(\?.*)?$ $1/index.html$2 [L]

some useful tricks:

all this and more can be found at the apache2 docs.

if there's an easy way to do all this then please please tell me, I miss try_files so much, holy cow.

programming

Anonymous comments will be held for review.