Top Nav

How to Redirect an Old Domain to New Domain via htaccess 301

apacheChanging domain names can be scary and unfortunately, it’s quite common. When migrating to a new domain name, not only do you risk breaking all your pages and links, but Google can also get cranky if all your indexed URLs end with a 404 – Page Not Found. Not only is this a terrible experience for your users, but it’s also a sure way to lose all your SEO juice aka Google Ranking. The good news is, if you’re running on an Apache website (which most of the internet is), there’s a simple solution.

Using .htaccess to Permanently 301 Redirect Old Domain to New Domain

If you haven’t made any changes to your site’s structure but are just transferring it, using the following code in your .htaccess file at the root of your old domain will not only redirect your users, it will also update Google’s index and pass along all your SEO Ranking.

<IfModule mod_rewrite.c>

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

</IfModule>

The code above is simple regular expression so you can do all kinds of nifty things with it. For example, if you want to redirect subdomains in addition to the root domain, you would use this code:

<IfModule mod_rewrite.c>

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

</IfModule>

You can also do things like redirect an old subdomain to a directory on the new domain (or vice versa). I did this when I redirected www.groovypost.com/forum/ to forum.groovypost.com.

<IfModule mod_rewrite.c>

RewriteCond %{HTTP_HOST} ^forum.olddomain.com$
RewriteRule (.*)$ http://www.newdomain.com/forum/$1 [R=301,L]

</IfModule>

This last example shows you to perform one-off redirects for individual pages. This could be handy if you kept the overall site structure the same (using one of the redirects above) however you want to change a few URLs to the new domain. Just use the following:

Redirect 301 /old/oldpage.html http://www.newdomain.com/newpage.html

Being regular expression code, the possibilities are endless. A key takeaway, however, be extremely careful when making these changes to your .htaccess file. Messing with this file can break your Apache webserver and take down your site. So test, test and test again before making any changes. Need help? Drop a comment here or on our free support forum.

More Reading:

, ,

3 Responses to How to Redirect an Old Domain to New Domain via htaccess 301

  1. solaris August 30, 2016 at 5:44 pm #

    Hi Brian,

    isn’t your first example code the same as the second one?

    • Steve Krause August 30, 2016 at 6:56 pm #

      Yes! You are correct. Article updated. I probably made the goof editing the piece. Thnx!

  2. solaris October 24, 2016 at 2:36 am #

    thx, you are welcome

Leave a Reply