Clinton Montague

Developer, learner of things, functional programming enthusiast, hacker, and all round inquisitor.

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:

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.