Rewrite websites with Apache .htaccess file

This article is about rewriting one website url to another site url.Say you have a production site running at www.abc.com and you have blocked the domain oldabc.com. Now you want to rewrites traffic coming to oldabc.com to www.abc.com.This can be done with two methods.

  • with dns cname entry.
  • with apache mod_rewrite.

Here we are going to explain how we can do this with apache.

Prerequisite:

1. You have the control over the hosting of source website and destination website.
2. You have write permission on the source website from where you are making the rewrite.
3. .htaccess file is enabled from the main configuration file with ‘AllowOverride’.

In this example we will use oldabc.com as the source domain and abc.com as the destination domain to which rewrite to be made.

1. Login to the source domain and make sure you have the mod_rewrite enabled in the apache.
On ubuntu systems you can check this by checking /etc/apache2/mods-enabled/.
It should have the ‘rewrite.load’ file linked in this directory. If the file is not available then it indicates that mod_rewrite is not enabled in the apache. You need to enable mod_rewrite with the below command.
a2enmod rewrite

On redhat based systems like centos,you should be able to check the mod_rewrite module at /etc/httpd/modules.
If mod_rewite is enabled then mod_rewrite.so file should be there.Also in your httpd.conf file the following
line need to uncommented.

LoadModule rewrite_module modules/mod_rewrite.so

2.Now you need to go to the document-root directory and add a file .htaccess file with the following content.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.abc\.com [NC]
RewriteRule ^(.*)$ http://www.abc.com/$1 [R=301,L]

Here ‘RewriteEngine On’ statement enables the rewrite mode with in this directory.
Second line is the rewrite conditional statement which says that if the request is not matching www.abc.com then follow the rewrite rule. ‘NC’ Indicates no case. Third line is the rewrite rule. Third line just says that what ever the request, rewrite the url to http://www.abc.com. R=301 is the rewrite code to browser and ‘L’ indicates as the last rule so that don’t follow any other rules.

You really don’t need to make any changes at the destination end.

3. Now open your browser and type http://myabc.com. You can see that your browser url got rewritten to http://www.abc.com.

References:
http://httpd.apache.org/docs/2.0/howto/htaccess.html

Leave a Reply