How to: 301 Redirect from one domain to another using mod_rewrite

By StrangeWork.com: Recently I created a new E-commerce website for a client of mine. I developed the new site as a subdomain under their existing domain (ex http://newsite.domain.com). Google ended up indexing around 4000 links from the subdomain I had created, so upon launching the new site I wanted to 301 redirect the subdomain links to the primary domain of the new site.

Sounds easy right? Of course! I quickly found many sites that recommended this rewrite rule using mod_rewrite:

RewriteRule ^(.*) http://domain.com/$1 [R=301,L]

However there is a problem with this method that no article seemed to address. This works great at redirecting from the subdomain (http://newsite.domain.com) to the new domain (http://domain.com), BUT if you navigate to http://domain.com you will hit an infinite loop.

So, how do you correct this problem? Easy, you need to create a rewrite condition to only apply the rule to your old domain or the subdomain in this case. Just add the following two lines to your .htaccess file in the root of your website:

RewriteCond %{HTTP_HOST} ^(newsite.)?domain.com$
RewriteRule ^(.*) http://domain.com/$1 [R=301,L]

Now this rewrite rule will ONLY apply to anyone who hits the old subdomain at http://newsite.domain.com and 301 redirect them to http://domain.com with the entire URL structure in tact. This method is easy to apply to a stand domain as well, just replace newsite in the above example with www.

I was pretty baffled at the amount of bad information there is on this method so thought I would share the proper method with everyone. Hopefully the update rewrite rules will help anyone having the same issues I had.

Enjoy this post? Be sure to subscribe to my RSS feed and my WordPress Tips and Tricks Newsletter! Also check out my WordPress books: Professional WordPress Second Edition & Professional WordPress Plugin Development

Comments

  1. Okay… THANK YOU. You just saved me a ton of time. I recently moved my blog from one domain to a new one, but hadn’t had time to tackle the problem of forwarding all the old post urls to the new site automatically.

    Your method above does exactly that, with only two lines of code. Sweet. :)

  2. Hey Noah! Glad I could help. I post articles like this for two reasons. I like to help people out and I know sometime in the future I’ll need this again so I know where to find it haha

  3. This helped me out a lot on a project I’m working on. Thanks a bunch!

  4. Thanks for the info.

    Would this work for a blog?

    Situation: client has been blogging for over two years at blog.olddomain.com and recently decided he would move the blog to it’s own newdomain.com

    So again, would this solution redirect all blog post on the olddomain to the new domain so that “http://blog.olddomain.com/old-post-title” would automagically point to “http://newdomain.com/old-post-title” ?