I’m putting this here because it took me a little bit of tweaking to actually get it
right. I always forget these .htaccess tricks and have to look them up. So I decided tp preserve this one here so I can easily find it next time I need it.
The trick is simple – I want to transform ugly looking URL’s with GET query string into neat looking, human readable addresses – kinda like the ones in Rails and similar frameworks. Let’s say you have a file called index.php in the directory foo that’s located in your web root. The script accepts three GET attributes and does something based on what they are. Your normal URL would therefore look like this:
It’s long, ugly and almost unreadable to the average user. I want my URL to look more like this:
Short, nice, readable and also easy to figure out. How do you accomplish this? With a little bit of htaccess magic. For me this setup worked:
Options +FollowSymlinks RewriteEngine on RewriteBase /foo/ RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?module=$1&action=$2&id=$3 [NC]
The RewriteBase thing is important if you want your application run in it’s own directory. Seriously, I spent like 20 minutes debugging this crap just because I forgot to put it here. You may or may not need it depending how you structure your app, but for me it seemed to simplify the pattern matching significantly.
The rest should be fairly self explanatory:
The ([^/]+) string will match anything but a slash character and save it in a variable ($1, $2 and $3 respectively). I then rewrite the URL the way it should look using the variables. The end effect is having the functionality of a long, ass-backwards query string combined with a simple and nice looking URL’s.
Also, this might be one of the shortest posts I have written on here in months. Enjoy the brevity while it lasts.