Apache’s Mod_Rewrite magics

October 24th, 2007

First lets see what is mod_rewrite

mod_rewrite is basically an apache module, using which we can play around with the URL’s

 Configuration

You need to cross check in your httpd.conf whether the following lines are present

LoadModule rewrite_module modules/mod_rewrite.so
AddModule mod_rewrite.c

If its not there, make sure to add it along with the other modules of apache which is mentioned in httpd.conf

again check for the directives mentioned for the directory block where your scripts reside.

thats something withing <Directory ..></Directory> tags

Inside which make sure you have the following line for AllowOverrides

AllowOverride All

See Apache’s documentation for further info on the above configurations.

Put into action

create a file with name .htaccess in your website/folder where you would like to make fancy url’s. say we have kept in a folder /fancy

Now edit the .htaccess file and type in following.

#### URL Rewriting example by Ramkumar – 08032007 #####

Options +Indexes
Options +FollowSymlinks
RewriteEngine on
RewriteBase /fancy
RewriteRule ^(.*)/(.*)/(.*).html$ index.php?c=$1&s=$2&p=$3 [L]
RewriteRule ^(.*)/(.*).html$ index.php?c=$1&p=$2 [L]
RewriteRule ^(.*).html$ index.php?p=$1 [L]

In the above code, see the line RewriteBase /fancy , which is very important, this says from where the rewrite rules need to be applied (the folder)

Now create a php page with following contents.

 <?php
$page=$_GET[‘p’];

if(isset($_GET[‘c’]))
echo “<h2>You are on category: <font color=’#FF0000′>”.str_replace(“-“,” “,$_GET[‘c’]).”</font></h2>”;
if(isset($_GET[‘s’]))
echo “<h3>You are on subcategory: <font color=’#FF0000′>”.str_replace(“-“,” “,$_GET[‘s’]).”</font></h3>”;

echo “<h4>You are viewing page: <font color=’#FF0000′>”.str_replace(“-“,” “,$_GET[‘p’]).”</font></h4>”;
?>

Open the page in browser under your webserver and try following URL combinations

/fancy/first/second/third.html

/fancy/first/second.html

/fancy/first.html

You are sure that the files corresponding to above URL’s  doesn’t exist in server, but you will still see a valid page (provided the mod_rewrite is working fine). If it works, thats the example of URL manipulation using mod_rewrite !!

One Response to “Apache’s Mod_Rewrite magics”

  1. nagendra says:

    good one for seo and programmers

Leave a Reply