URL Rewriting Fun Wednesday, August 25, 2010
A new addition to my blog that is pretty neat is how I'm creating my URLs. I recently decided to dive into the art of URL rewriting! I thought it was really difficult and would take all sorts of voodoo to get it to do what I wanted, but within a couple of tries I was able to make some pretty advanced URL rewrites.
First of all, if you visit my site from identi.ca (or Twitter), you'll notice my URLs have changed from something like http://cassidyjames.com/blog/?post=57 to http://cassidyjames.com/b/57. This is important especially in micro-blogging because it shaves off ten whole characters. That's over 7% of an entire dent (or tweet)!
I achieve this URL rewriting by modifying the hidden file named .htaccess stored in the root directory of the server. I just had to simply include the line...
RewriteEngine On
...and BAM! the rewrite engine is on (simple enough, right?). Next, I created a rewrite rule on the next line:
RewriteRule ^([a-zA-Z0-9_-]+)$ $1.php
This rule says that my site's URL followed by any character(s) will route to the character(s) plus .php. This means that if I have a file, say "test.php," you can get to it by visiting http://cassidyjames.com/test. This is nice to be able to hide the ".php" from normal users (who don't want to have to type it in) and more advanced users (from whom it obfuscates your server technology).
The next rule I added is actually for the blog specifically. The rule...
RewriteRule ^b/([a-zA-Z0-9_-]+)$ blog/?post=$1
...means that http://cassidyjames.com/b/57 now points to http://cassidyjames.com/blog/?post=57. This allows the blog URLs to be both shorter and prettier.
My final .htaccess rewrite rule I'm going to show isn't actually used on my site, but rather on a church's site I'm helping with. The rule...
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ $1_$2.php
...allows the site admin to use a simple file naming convention to create faux subdirectories. The file "about_ourteam.php" can be created, but the link to it is simply http://stonechurcheagan.com/about/ourteam. This is nice because they don't have to worry about creating directories but they get the advantage of having prettier URLs throughout the site. The only important thing is that all site URLs begin with the root "/" to make sure links and images function properly.
Do you have any fun URL rewriting tips or tricks? Have questions on how to implement this on your site? Let me know in the comments!