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

By 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 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 ^(.*)$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 ( to the new domain (, BUT if you navigate to 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.)?$
RewriteRule ^(.*)$1 [R=301,L]

Now this rewrite rule will ONLY apply to anyone who hits the old subdomain at and 301 redirect them to 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 Third Edition & Professional WordPress Plugin Development


  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 and recently decided he would move the blog to it’s own

    So again, would this solution redirect all blog post on the olddomain to the new domain so that “” would automagically point to “” ?