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.