Thursday, August 20, 2009

Rewriting URLs with Apache mod_rewrite

I've noticed a growing trend on message boards where rewriting the URLs is becoming quite common. So instead of the URL being http://www.a-b-c.com/forums/board.pl?action=view&category=cars the URL is http://www.a-b-c.com/forums/cars or something similar. This is not only easy to remember/bookmark it allows the spiders to crawl the pages more easily and you have the added benefit of moving things on the backend without breaking the links.

This can easily be done with APache's mod_rewrite module. Make sure .htaccess is enabled in httpd.conf and mod_rewrite is installed. Then create a .htaccess file with the following contents:

RewriteEngine on
RewriteRule ^articles/([^/\.]+)/?$ /cgi-bin/displayArticle.pl?$1 [L]

Any request of the form http://www.whatever.com/articles/abc will now go to http://www.whatever.com/cgi-bin/displayArticle.pl?abc

There's a lot more to it and even more to mod_rewrite in fact there's a whole book (or two?) on mod_rewrite out there.

No comments:

Post a Comment