Mod_rewrtie rule 101

Mod_rewrite is a complex subject and often time it could be very confusing for people starting out trying to use this great tool!

I will do some really basic mod_rewrite rules here for those that is trying to get some basic understanding of mod_rewrite rules

IMPORTANT NOTE: the left side of the rule is what you will see in the browser not the rewritten URL on the right

Here are the detail explanation line by line

RewriteEngine on

- turn on rewrite

#RewriteBase /test

- uncomment to use this if you do this in a test folder

RewriteBase /

- use this if you do this on your web root

RewriteRule ^/?test\.html$ test.php [L]

- rewrite from test.html to test.php

RewriteRule ^/?profile/([0-9a-zA-Z_]+)/([0-9a-zA-Z_]+)/([0-9a-zA-Z_]+)$ profile.php?uid=$1&name=$2&other=$3 [L]

- rewrite from /profile/1/john/music to profile.php?uid=1&name=john&other=music

Below are files that you can just copy and paste to try out and see if you get the result like the sample run... Enjoy!

file: .htaccess

RewriteEngine on
#RewriteBase /test
RewriteBase /
RewriteRule ^/?test\.html$ test.php [L]
RewriteRule ^/?profile/([0-9a-zA-Z_]+)/([0-9a-zA-Z_]+)/([0-9a-zA-Z_]+)$ profile.php?uid=$1&name=$2&other=$3 [L]


file: profile.php

<?php
echo "from profile.php";
echo "hello " . $_GET['uid'] . " with name : ".$_GET['name']. " with other : ".$_GET['other'];;
?>

file: test.html

This is the HTML file.

file: test.php

This is the PHP file.

Sample runs:

URL in a browser:
http://yoursite.com/profile/1/john/music

rewrite to:
http://yoursite.com/profile.php?uid=$1&name=$2&other=$3

and will show:

from the "profile.php" will output this text below:

hello 1 with name : john with other : misc

URL in a browser:
http://yoursite.com/test.html

rewrite to:
http://yoursite.com/test.php

and will show:

This is the PHP file.

Forums: