Use .htaccess to Redirect your Website to a New Domain Name

Use .htaccess to Redirect your Website to a New Domain Name

By Aaron F. October 22nd, 2014

Hello everyone!

As most of our regular readers & customers know by now, I recently went through the painstaking task of rebranding my business from af Creative, to the new & improved Aaron Fagan: Web Architect! What this meant from a website perspective is that we had multiple old domains, and we needed a way to securely and easily redirect all of our old content to our new domain.

Its easy enough to use PHP or even Javascript to redirect to a top level domain (, but what about the subpages, blog entries, etc? The structure of our URL's was staying the same, just the primary domain was changing.

Using .htaccess is no doubt the way to go in this case. With some playing around, we were able to redirect all of our old domain names to the new one, for example redirects to Likewise, redirects to, and so forth. The other benefit is that this is a safe way to do a 301 redirect, which tells Google and other search bots that the old domain is no longer being used, but to use the new domain for future indexing.

Please see the exact code below that I used to forward my domains. I will take a moment to explain what does what, as well as provide an example for multiple domains pointing to the same domain, and multiple domains pointing to different domains.

RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L]

Line 1: Tells your server that it is OK to rewrite the domain name in the address bar of the users computer. This line is required, do not forget to include it!

Line 3: Tells the server what old domain was accessed, whether it was typed in to the address bar of a browser, or a link from a search engine.

Line 4: As you have guessed by now is the new domain name to forward traffic to.

As this appears above, it will redirect all subpages to the new domain as well. Now, lets take a look at multiple domains going to the same domain:

RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L] RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L] RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L]

Again, this is pretty strait forward. As mentioned before, line 1 is required. It only needs to appear one time, and it must be the first line before your redirects. To add more redirects, simply copy lines 3 & 4 over and over, as in this example, and modify accordingly.

To send multiple domains to multiple different domains, its similar to the above. Simply modify the RewriteRule to suite the new domains, as follows.

RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L] RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L] RewriteCond %{HTTP_HOST} ^(www.)?$ RewriteRule ^(.*)$ "$1" [R=301,L]

Thanks for reading!

Topics: Cloud Infrastructure, Web Design & Development