Quick start guide to mod_rewrite

The Apache mod_rewrite module turns out to be a very useful tool when you’re building PHP applications. The unfortunate souls who chose to do the CS 462 project in PHP last winter semester had to learn it. I had never touched it myself until this semester when I needed it for a project in CS 360. It turned out to be pretty easy to use. Here’s a simple quick start guide:

First, make sure Apache has the mod_rewrite module installed. In Ubuntu, you can execute this command:

sudo a2enmod rewrite

Now, create an .htaccess file in your site’s root folder. Here’s an example:

RewriteEngine On
RewriteRule ^list/popular(.*)$ index.php?list-popular$1[QSA]
RewriteRule ^list/recent(.*)$ index.php?list-recent$1[QSA]
RewriteRule ^$ index.php

The [QSA] at the end of the line means “query string append”. You can find a list of the other possible flags here. You’ll find good documentation on the whole module there as well.