Wednesday, February 06, 2008

Apache ReWrite Module

Apache has a very powerful tool (mod_rewrite) which can be used to redirect/rewrite requested URLs on the fly.

To use this module, you can configure apache with the '--enable-rewrite' option before compilation. Then, set 'RewriteEngine on' in the httpd.conf to start using it.

For complete details, please go to http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html.

I will give a brief example which redirects all requests on http://www.localhost.com/ to http://localhost.com/ (I needed to do something like this for a site) and any request starting with '/redir/xyz' will execute '/test.php/redir/xyz'.

Following is copied from the httpd.conf.

...
...
NameVirtualHost 127.0.0.1:80

<VirtualHost 127.0.0.1:80>
ServerAdmin your@email.com
DocumentRoot /usr/local/apache/htdocs
ServerName localhost.com
ServerAlias localhost.com
RewriteEngine on
RewriteRule ^/redir/(.*) /test.php/redir/$1 [QSA,PT,L]
RewriteLog logs/rewrite_log
RewriteLogLevel 3
ErrorLog logs/local_error_log
CustomLog logs/local_access_log common
</VirtualHost>

<VirtualHost 127.0.0.1:80>
ServerAdmin your@email.com
DocumentRoot /usr/local/apache/htdocs
ServerName www.localhost.com
ServerAlias www.localhost.com
RewriteEngine on
RewriteRule ^/(.*) http://localhost.com/$1 [QSA,R,L]
RewriteLog logs/rewrite1_log
RewriteLogLevel 3
ErrorLog logs/local1_error_log
CustomLog logs/local1_access_log common
</VirtualHost>

No comments: