mod_rewrite semi tutorial
November 1, 2008
Please note!! I have shamelessly stolen this article from my old and (even if I do say so myself) rather boring blog. So please ignore the terrible writing style! I’ll rewrite this article in the future, but until then, I present you with version 1.0
There are a lot of tutorials out there regarding apache’s very powerful mod_rewrite module. They always seem to offer every solution except the one which you want! Here is an example of a mod_rewrite script which I commonly use.
RewriteEngine on
# Directories which we allow the browser to see
RewriteCond %{REQUEST_URI} !^/css
RewriteCond %{REQUEST_URI} !^/js
RewriteCond %{REQUEST_URI} !^/uploads
# Redirect all other 'directories' to the main php page
# for it to work out what to do.
RewriteRule ^(.*)$ index.php?/$1 [L]
There are a few directories which I WANT the browser to be able to access, the images folder for example. There are a lot of directories I DON’T want the browser to be able to access, and this is where my solution comes into play.
A quick code run-through:
- Line 1 turns the module on
- Lines 4-6 are the directories which the user is allowed to access. In pseudo-code it would look something like this:
IF (the url doesn’t start with /css AND the url doesn’t start with /js AND the url doesn’t start with /uploads)
THEN do the url rewriting.The scary looking %{REQUEST_URI} is just an apache environment variable. - Line 10 is the ‘interesting’ bit. The ^ means that the pattern starts at the beginning of the url, the $ means that the pattern finishes at the end of the url, and the .* means match any charactor any number of times. Because the .* is in parentheses, it is then stored in the variable $1. The next bit is easy, just tell apache where you want to redirect to, in this case /index.php?/whatever/the/url/was.
Another great thing about doing it this way is that it’s not easy to get a 404 error, apache just re-writes the url and passes it to index.php, which we know exists so if the worst comes to the worst, it can always just show the home page.
If you need a bit of bed-time reading, I recommend the apache documentation on mod_rewrite. There is a great cheat sheet over at htaccesscheatsheet.com.