Redirection with mod_rewrite

Understanding Redirection with mod_rewrite.

The Apache module, mod_rewrite, is typically used to transform URLs from one form to another. It can also be used for permanent redirection. The rewriting rules can be placed in httpd.conf (for server-wide rules), or in .htaccess files (for directory-specific rules). Consider the following example that is in the .htaccess file of this website:

rewriteEngine on

rewriteRule ^contact\.php$ [R=permanent,L]

The first line tells Apache to turn the mod_rewrite engine on. The second line tells mod_rewrite to match requests where the URI is exactly contact.php. The ^ and $ match the beginning and end of the expression, respectively, and the \ is used to escape the period, which otherwise would match any character. After the match pattern is a space, and then the substitution. In this case, I want the server to substitute contact.php with

In brackets are the comma-separated rule flags. The R=permanent flag tells Apache to issue a permanent redirect 301 response, with the location as the substituted URL. The L flag tells mod_rewrite that no other subsequent rules should be processed.

Note that I specified the full destination URL in the substitution, because otherwise mod_rewrite uses the short form of my hostname To avoid Google indexing issues, I’ve redirected all non-www traffic to the www prefixed host. I also redirect the default, index pages to the root directory. The rules to achieve this are as follows:

# redirect all non-www traffic

RewriteCond %{HTTP_HOST} ^yourdomain\.com$

RewriteRule ^.*${REQUEST_URI} [R=permanent,L]


# Redirect aliases of home page to the root website

rewriteRule ^index\.(php|html|htm) [R=permanent,L]

we have provided this example to understand the mod_rewrite documentation. The mod_rewrite module offers a very powerful and effective way to perform redirection. It is preferable to use mod_rewrite over a server-side script. The drawback is the steep learning curve, requiring you to learn both its syntax and the syntax of regular expressions.


Still don’t have a hosting plan? Buy Linux shared hosting plans starting from $2.95/ Per Month with cPanel Control panel,¬†softaculous, siteapps and many more features….