mod_rewrite is awesome!

Submitted by Emil on Thu, 07/17/2008 - 21:31

mod_rewrite is an amazing module for Apache! First time I came in contact with it was when installing Drupal once a long time ago. Back then, I thought it was extremely awesome and guessed it was really hard to implement myself. Yesterday, I started using it and found that it was in fact quite easy.

What it does is to rewrite URLs by using regular expressions. For example, you can turn the ankward address forumThread.php?id=3&page=2 into the more exciting forum/3-2. First of all, it looks very nice and getting your pages indexed in the search engines' databases is easier.

The approach I took was to add the following lines to my .htaccess in the web root:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ rewrite.php?q=$1 [L,QSA]
</IfModule>

The first line tells Apache to see if mod_rewrite is present at the server. If so, the next line turns the rewrite engine on. The next two lines are conditions for line five where the actual rewrite rule is set. Line three makes sure the rule isn't used if there is a real file matching what the user was looking for and line four does the same for directories.

If no files or directories have been matched, the fifth line tells Apache to redirect all requests to a script named rewrite.php and send the request url as parameter q.

In rewrite.php, the last piece of magic is done by simple checks. For example:

<?php
if (preg_match("/^forum\/(.*)-(.*)$/", $q, $matches)) { $_GET["id"] = $matches[1]; $_GET["page"] = $matches[2]; include "forumThread.php"; }
?>

makes requests like forum/3-2 be redirected to forumThread.php?id=3&page=2.