Apache 2 mod_rewrite

 

Overview

Enable mod_rewrite

* Edit httpd.conf and uncomment this line:

LoadModule rewrite_module modules/mod_rewrite.so

mod_rewrite Comments

* You can use RewriteEngine off to ignore rewrite statements

RewriteEngine off  
 
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]  
 
RewriteRule .? http://www.example.com%{REQUEST_URI} [R=301,L]  
 
RewriteEngine on

Logging

* Using LogLevel directive
* Apache 2.2 and below:

RewriteLog /var/log/httpd/rewrite.log
RewriteLogLevel 9

* Apache 2.4 and above:

# most verbose is trace8
LogLevel alert rewrite:trace3

mod_rewrite Flags

* last|L: terminate rewrite conditions/rules
* nocase|NC: ignore case
* redirect|R: default to HTTP302 (redirected temporarily). Use [R=301] for permanent redirect
* qsappend|QSA: pass through existing query strings
* forbidden|F: Apache will issue 403 response
* ornext|OR: logical OR condition. Default is AND condition
* next|N: restart rewrite process from the first rule

Setup URL Rewrite

Use httpd.conf

* Create a test config file: /etc/httpd/conf.d/testmodrewrite.conf with the following content to redirect all request starting with test to google.com:

<IfModule rewrite_module>
RewriteEngine On
RewriteLog /var/log/httpd/rewrite.log
RewriteLogLevel 9
 
# Redirect any request starting with test to google.com
RewriteRule ^/test(.*) http://www.google.com/ [P]
</IfModule>

* Point your browser to test.html and you’ll be redirected to google.com

Use .htaccess

* Allow .htaccess usage in httpd.conf file:

<Directory "/var/www/html">
    # Allow .htaccess
    AllowOverride All

* Create .htaccess file in the test directory, e.g. /var/www/html

RewriteEngine on
 
RewriteRule ^/?test.html$ http://www.google.com [L]

* Point your browser to test.html and you’ll be redirected to google.com

Modify Query String

* Manipulating the Query String

RewriteCond %{QUERY_STRING} (.*(?:^|&))key=val((?:&|$).*)
RewriteRule /test(.*) /test.html?%1other_val%2
 
RewriteCond %{QUERY_STRING} ^key=(.*)$ [NC]
RewriteRule ^/test(.*) /test.html?key=%1
 
RewriteCond %{REQUEST_URI} ^/test1 [NC]
RewriteCond %{QUERY_STRING} ^key=(.*)$ [NC]
RewriteRule ^/test(.*) /test.html?key=%1

References

* http://www.sitepoint.com/apache-mod_rewrite-examples/

This entry was posted in apache. Bookmark the permalink.