Tuesday, September 23, 2008

RewriteMap PRG By Example Using PHP For Apache Mod_Rewrite

For the purpose of Search Engine Optimization many web developers uses apache mod_rewrite module for URL rewriting so that they can produce search engine friendly URLs. Although for most of the purpose RewriteRule directive is enough to get the job done but for the greater flexibility one can use RewriteMap directive. Unfortunately I didn’t see any example on the web for RewriteMap in details. So I investigated the matter in detail myself and after spending hours and trial and error I finally succeeded in using RewriteMap. I will show you how to do it in both Windows and Linux. Even though the differences are minor but they are enough to grind your brain into syrup (at least this is what happened with me). To use RewriteMap these three steps are needed to be done.

* Change httpd.conf file in Apache conf directory.
* Write RewriteRule in .htaccess (or in the other apache configuration files).
* Write your PHP script file.

RewriteMap example

Although chances are lower that you will be running Linux in your local machine but the fact is when we enter in the arena of WWW the scenario changes dramatically. Yes, welcome to the world of Linux. Internet is powered mostly by Linux so we will take our first example on Linux OS.

Change Configuration file.

open your httpd.conf file and add these lines in your configuration file.
Codes for Apache Httpd.conf for Linux



RewriteEngine on
RewriteMap links "prg:/usr/bin/php /var/www/vhosts/example.com/httpdocs/rewriting_script.php"

Codes for Apache Httpd.conf for Windows



RewriteEngine on
RewriteMap links "prg:C:/Progra~1/PHP/php.exe d:/localhost/rewrite_test/rewrite_url.php"


‘links’ is the label given so that we can refer to it later. In doubles quotes is the path to php interpreter and then full path to your rewriting script. Note that how “Program Files” folder is converted into DOS compatible file path. It is necessary otherwise it wont work. Put these line of codes after all modules have been loaded using LoadModule directive in httpd.conf file. Put it in the wrong place for example under directive and then test configuration of apache web server and you will get an error saying “RewriteMap not allowed here”.

No comments: