I have recently lost my “URL rewriting virginity”, in that I have set up rewriting for the first time, using apache’s .htaccess file. For those that don’t know, .htaccess is a file kept in the root folder of the site that it will apply to. The file contains rules that affect the behaviour of your website.
It took me browsing several forums before I managed to learn how to rewrite both static URLs and URLs with dynamic parameter strings and values.
The apache module I found is called MOD Rewrite, and can be called from within a .htacces file.
A quick definition of URL rewriting in the capacity that I have required its use:
I use the GET keyword in PHP to store parameters provided in my URL to variables that I will then use throughout my PHP document. Doing this really helps me, because if I have multiple items of content that I want to pull out of a MYSQL database into a web page template, I can do so by providing MYSQL with the name or ID number of that content item.
Now that I have parameter values in my URL, it tends to look rather longwinded and technical such as: http://www.mysite.com/index.php?id=1&category=1&title=1
I would like to change this hideous & cumbersome URL to something a bit neater. In SEO, some search engines discard everything after the question mark, therefore not bothering to put your page in their index.
My URL, once rewritten will read something like: http://www.mysite.com/home/1/category/title. How do I go about this? Well I start my .htacces file:
RewriteRule ^home/ index.php [NC]
In this example, anyone who types http://www.mysite.com/home/ into their address bar will end up seeing the output of my index.php document. That’s perfect, exactly what I wanted. Now if I want to add a dynamic, changing parameter such as the id of the content item, I add this line to .htaccess:
RewriteRule ^home/id/([^_]+) index.php?id=$1 [NC]
This will now replace ?id= with home/id/, and the variable id (22 for example) will go after, as in home/id/22.
To add a page title and category to this, I will write the rule as follows:
RewriteRule ^home/id/([^_]+) /([^_]+)/([^_]+) index.php?id=$1&category=$2&title=$3 [NC]
Well, I hope you managed to make this work on your server, but if you had trouble, you can read more detail about using MOD Rewrite here: .htaccess tricks and tips.. part two: url rewriting with mod rewrite.
I found this unexpected surprise quite annoying, but it certainly hasn’t put me off rewriting my URLs, which just looks so much better to users, and my keyword rich post titles get seen in the URL by search engines! I will simply plan my URL structures accordingly in future.