URL Manipulation using mod_rewrite

December 16, 2007

What It is
mod_rewrite is frequently called the “Swiss Army Knife” of URL Manipulation. mod_rewrite is used for rewriting and redirecting URLs dynamically, using powerful pattern matching.
The most common use of mod_rewrite is to make ugly URL most attractive. For example , say our URL looks like http://www.example.com/index.php?cmd=login , and we want to show the url in the address bar as http://www.example.com/login. To do this we need to use the following.

# First make the RewriteEngine On
RewriteEngine On
# Translate login to /index.php?cmd=login
RewriteRule ^login$ /index.php?cmd=login [L]

Installing mod_rewrite
Because of its popularity, mod_rewrite is now included with all common Apache distributions. We can verify if your Apache installation has the mod_rewrite module by looking for a file named mod_rewrite.so under the modules folder in our Apache installation directory.
To make sure open up the httpd.conf file in the Apache conf folder and find the following
#LoadModule rewrite_module modules/mod_rewrite.so
The initail # means it commented out , so to install the mod_rewrite remove the # and restart the Apache. Thats all for mod_rewrite installation.

Testing mod_rewrite
We can write rules in httpd.conf file or in .htaccess file to work for per directory basis. .htaccess is used for customised rules for any specific directory.
Lets create .htaccess file in htdocs folder. and a index.php file that basically dump the POST variable.

index.php file goes as follows
// index.php file that basically do nothing only dump the post variable for this example
$cmd = $GET['login'];
if($cmd == ‘login’)
{
echo ” You are in login Page”;
}
else
{
echo “Elsewhere”;
}
# First make the RewriteEngine On
RewriteEngine On
# Translate login to /index.php?cmd=login
RewriteRule ^login$ /index.php?cmd=login [L]

Now test the above rule using the url : http://www.example.com/login and see the output.

For more info please visit : Apache Mod Rewrite Rule Doc

Entry Filed under: Apache. Tags: , , , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Me in Brief

Expert Rating Certified Professional PHP5
Hi I am Shaikhul Islam Chowdhury Shaymol,
Currently working at Internet BS Corp as a Software Engineer.
I like to explore LAMP and other Web Technologies.
 

My LinkedIn Profile

View Shaikhul Islam Chowdhury Shaymol's profile on LinkedIn
 

Pages

Categories

Links

RSS PHP Magazine

RSS PHPGeek

Archives

Photos from FlickR

graduate

RoomMates@RashidHall.KUET

faruk monir monil n me

yamin me n tani apu

me@home

More Photos