Thursday, March 17, 2011

The Apache "mod_rewrite": Best SEO Tool, Must Have Web Development Skill

Apache mod_rewrite is a module of Apache web server which allows server side manipulation of the URLs. (If you need help with Apache web server, read this first). This means that you can redirect http://abc.com to http://zxy.com without changing the URL in the client's address bar. All you need to know is the syntax of mod_rewrite (which I'll tell you here) and some regular expressions (though it is not mandatory). A great cheat sheet for regular expression is available from AddedBytes.com. If you want to know who uses mod_rewrite then let me tell you, whenever you hear of something known as "clean URL", most probably mod_rewrite is behind it. Wordpress, Drupal and many other blogging platforms and CMSs produce clean URLs using mod_rewrite.

To ensure that mod_rewrite is enabled on your apache, just make sure that your apache config file has the following line uncommented:
LoadModule rewrite_module modules/mod_rewrite.so

If it was commented before and you have uncommented it manually, then you need to restart your apache web server. To check if mod_rewrite has been enabled or not, just create an empty file anywhere in your web root and write the following line:
<!--?php phpinfo(); ?-->

Open this file in any web browser and check out apache2handler. mod_rewrite would appear there if it is enabled successfully.
Now let us write some basic mod_rewrite rules for real. Suppose tha you want to redirect all the traffic to you website to a fixed URL (this generally happens when you take down your site for update or maintenance). All you need to do is write the following lines in your .htaccess (more on .htaccess in some other post):-
RewriteEngine On
RewriteRule .* maintenance.php

First line will turn the Rewrite engine on (it is usually on but we like to be on the safe side). The second line will capture all the incoming URL (.* is the regular expression here) and will redirect it to the maintenance.php in the web root.

Now let us create a more useful rewrite rule. Something similar to what is used to create clean URLs. Consider a website which takes input in the form http://abc.com/name.php?q=aditya. This looks ugly and is not search engine friendly. We would like to have something like http://abc.com/name/aditya. This would be nice and easy to remember. For this let us create a rule for mod_rewrite.
RewriteEngine On
RewriteRule ^name/(\w+)/?$ name.php?id=$1

The Rewrite engine is going to examine the incoming URL requests and (time to open the regular expression cheat sheet if you do not master it) convert the friendly URL into the URL understandable by the server.

We can also create custom error messages using mod_rewrite. For creating a 404 Not Found message, follow the rules given below: