My name is Max, and I abuse .htaccess.
The site to which this blog is attached uses .htaccess as part of its process and it serves 2 major purposes:
- I use it to mask the fact that it runs on PhP
- Passes all requests to a single script which, based on the url, feeds the correct page
Why bother you ask? Well so I can use my own templating system and frankly because I’m a computer scientist and am really bad at not re-inventing the wheel.
So that I have a backup and some explanation of what I’ve done next time I look at it and swear at my incomprehensible code the following is a transcript of the major sections:
ErrorDocument 401 /err/401.html
ErrorDocument 403 /err/403.html
ErrorDocument 404 /err/404.html
ErrorDocument 500 /err/500.html
Basically where to route the user on a given error, not actually used as it should be entirely handled by the site-engine.
Options +FollowSymlinks
RewriteEngine on
Turns on the ability to forward the user to another location
RewriteCond %{http_host} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]
Makes www. unaccessible, this is just for some basic consistency across the site. The R=301 makes it an actual http redirect, the NC tells it to ignore case and the L tells it that this is the last command and the rest of the file should be ignored.
<FilesMatch "\.htaccess$">
Order deny,allow
Deny from all
Satisfy all
</FilesMatch>
This stops the .htaccess file itself from being accessible.
RewriteCond %{http_host} !^3void.com$ [NC]
RewriteRule ^(.*)$ $1 [NC,L]
This is to allow subdomains to be used normally without passing through the site-engine.
RewriteCond %{request_uri} ^\/js\/.*$ [NC]
RewriteRule ^(.*)$ $1 [NC,L]
This speeds up the javascript access by not sending it to the script, actually required for tiny mce and possibly other external libraries to work properly.
RewriteCond %{HTTP:RedirectedToGenPage} !^true$ [NC]
RewriteRule ^[PAGE-GENERATOR-SCRIPT].php(.*)$ / [F,NC,L]
Checks to see if we’ve already been sent to the [PAGE-GENERATOR-SCRIPT] and if we have we can stop processing and let it run as normal.
RequestHeader set RedirectedToGenPage "true"
Sets a header on the request saying we’ve now been sent to the [PAGE-GENERATOR-SCRIPT]. This is important because I don’t want the script to be accessible directly so people have to use the site as a normal site and can’t directly got to [PAGE-GENERATOR-SCRIPT].php?uri=[WHEREVER].
RewriteCond %{request_uri} !^.*[PAGE-GENERATOR-SCRIPT]\.php.*$ [NC,OR]
RewriteCond %{request_uri} ^\$ [NC]
RewriteCond %{QUERY_STRING} ^(.*)$ [NC]
RewriteRule ^(.*)$ /[PAGE-GENERATOR-SCRIPT].php?uri=$1&%1 [NC,L]
Performs the actual redirect, this time it’s not a proper http redirect, we just send the current request to [PAGE-GENERATOR-SCRIPT].php.
Not sure why I do this.