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 and you have blocked the domain Now you want to rewrites traffic coming to to 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.


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 as the source domain and 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 file should be there.Also in your httpd.conf file the following
line need to uncommented.

LoadModule rewrite_module modules/

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 ^(.*)$$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 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 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 You can see that your browser url got rewritten to


Leave a Reply