Articles

Mod_Rewrite for Cruft Free URLs

January 07, 2007 (usability, lamp)


This website uses Apaches mod_rewrite to create cruft-free URLs. A cruft free URL is one that has no file name or file extension or query string information. The URL is meaningful to a human reader and not cluttered with information used by the underlying scripts.

To add mod_rewrite to your site you first must find a host that supports mod_rewrite. I use Dreamhost.com because they offer this and many other services.

The second step is setting up a proper site structure. In my root folder I have a directory name articles. In that articles directory is an index.php file. Also in that folder is a file named article_detail.php.

In a non mod_rewrite website I would link an article from index.php to article_detail.php by creating a link article_detail.php?article_id=27.

article_detail.php would then parse out the Id number, load that article from MySQL and display it.

However, in a mod_rewrite website the link from index.php can be anything you want and I have chosen to use the article title as the link. The link from index.php is now articles/mod_rewrite_for_cruft_free_urls/. Human readable and no cruft.

This is accomplished by creating a .htaccess file and putting it in the root directory of your website. As a sample, here are the contents of my .htaccess file.

Options +Indexes
RewriteEngine on
RewriteBase /
RewriteRule ^prioninteractive.com/article/(.*)/$ prioninteractive.com/articles/article_detail.php?article_id=$1 [L]

The first three lines are standard mod_rewrite commands that need to be at the top of the page. The real action, for the articles section of the site, starts on the fourth line with the RewriteRule.

This rule is stating that any URL request that matches the first (regular) expression should be redirected too the second expression. In this case, a URL with a nice article name, the (.*) part, should be sent to article_detail.php?article_id=$1 where $1 is the (.*) from the first expression and is subbed in automatically by mod_rewrite. You’ll notice that in this example I am sending the title of the article as the article_id to article_detail.php. article_detail.php parses out the title and uses it to find the article record in MySQL. Therefore, article titles need to be unique, which is not difficult to ensure.

Mod_rewrite is a very powerful tool and this example shows how a superficial use of the tool can result in a cleaner website.