What is Mod Rewrite and How to Use It

June 17, 2009

What is mod rewrite

In technical words mod rewrite is a way to direct server to respond in a specific way to request it receives. In words understandable for general public mod rewrite allows creating user and search engine friendly links (http://superiorwebsys.com/client/19/Laptops_Buyer/ or http://laptopsbuyer.ca/getQuote/brand/HP/)

Why would you want to use mod rewrite

First of all it is user-friendly, looking on URL visitors to the site can understand where they are, and it is easier to memorize those kind of links.

Link with mod rewrite: http://laptopsbuyer.ca/getQuote/brand/HP/

Link without one: http://laptopsbuyer.ca/getQuote/index.php?brandsID=19

Second reason is search engines, when they see specific keyword in URL they give you a higher rating. Yahoo loves it the most out of Google, Yahoo and MSN.

How to do mod rewrite on Apache server

You need to create a file in same folder as you have your index.php file and call it .htaccess

Here is what we used inside .htaccess on the site http://laptopsbuyer.ca

RewriteEngine On

RewriteRule ^getQuote/brand/(.*)$       /getQuote/index.php?modRewriteON=yes

ErrorDocument 404 /

First line is to tell the server that you want to turn on mod rewrite

Second line redirects all URLs that starts with get getQuote/brand/ and finnish with anything (.*)$ to /getQuote/index.php?modRewriteON=yes

Third line redirects all requests to pages that do not exist to the home page of the site

Here is the code inside /getQuote/index.php

<?
//Check if this file is accessed with mod rewrite
if(!empty($_REQUEST["modRewriteON"]) && $_REQUEST["modRewriteON"]=="yes")
{
    
$urlArr=explode("/",$_SERVER['REQUEST_URI']);
    
$brandName=$urlArr[3];
    
//get brand ID from the title
    
$sSQL="SELECT * FROM brandTable WHERE brandTitle='".$brandName."'";
    
$result=mysql_query($sSQL) or die ("MySQL err: ".mysql_error().
"<br />".$sSQL);
    if(
$row mysql_fetch_assoc($result))
    {
        
$brandsID $row["brandsID"];
    }
    
/*Write brand ID into request so no matter if mod rewrite is used
        or page accessed straight without it
http://laptopsbuyer.ca/getQuote/index.php?brandsID=19*/
    
$_REQUEST["brandsID"]=$brandsID;
}
$brandsID=(!empty($_REQUEST["brandsID"]))?addslashes($_REQUEST
[
"brandsID"]):"";
?>

Samples

http://laptopsbuyer.ca/getQuote/brand/HP/
http://superiorwebsys.com/client/15/Easy_SMS_Reminder/
http://studentsmetro.com/textbooks/college-textbooks-for-sale/

Michael Pankratov