Programming is a wonderful mix of art and science; source code is both a poem and a math problem. It should be as simple and elegant as it is functional and fast. This blog is about that (along with whatever else I feel like writing about).

Thursday, November 15, 2007

Apache Rewrite Rules

Everybody likes websites that have good, clean URLs. On a minor little project I'm working on on the site, I wanted to give that a try. So instead of seeing a URL like /index.php?username=user1&view=feeds, you'd see /user1/feeds. It's kind of cool ... and remarkably easy!

One assumption this particular projects makes is that index.php is the only page that'll be viewed. It checks the query string parameters and changes its behavior depending on that. I don't personally like this method, but it makes it easier to handle the rewriting rules.

Here's the .htaccess file you're going to want to put into your webroot directory:

RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)/?$ index.php?username=$1
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z]+)/?$ index.php?username=$1&view=$2
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z]+)/([a-zA-Z]+)/?$ index.php?username=$1&view=$2&action=$3
RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/?$ index.php?username=$1&view=$2&action=$3&id=$4


So that seems simple enough. The first option on each line is the regular expression that you want to match. Each match within a set of parentheses corresponds to the $1, $2, etc, flags in the second option. The ^ at the beginning and the $ at the end are regex symbols signifying the beginning and end of the string, respectively. the /? right before the $ on each line makes it so the rule will match the URL whether there's a trailing slash or not. (For example, /user1 and /user1/ will work in exactly the same way.)

Thanks ... and enjoy!

No comments: