301 Redirect with Apache and mod_rewrite

Just this past week I stumbled upon a new problem. I have a website which will be soon changing domain names. The hosting will stay the same, only switching domain names. One of the first problems I want to watch out for is page rank on various search engines and do a 301 redirect. Secondly, I want to make sure if anyone has a page on this site bookmarked, it still works properly while redirecting to the new domain. Finally I want minimal downtime during this transfer. My question to myself was how do I do this, and the answer was quite simple since I was using Apache and mod_rewrite. So to get started I gathered the possible domain names I'm dealing with:

  • www.olddomain.com
  • olddomain.com
  • www.newdomain.com
  • newdomain.com

Ok, so you are saying this is pretty obvious, but I want to keep this in mind while creating my mod_rewrite. The current set up has both domains pointing to the same directory on the server, so they currently work, but we want to get completely away from that olddomain.com, but until then we want to keep it up. Our solution lies within an .htaccess file within the root of our directory. We simply want to process a redirect from anything access on olddomain.com(or www.olddomain.com) to www.newdomain.com. To keep it simple I simply redirect to www.newdomain.com, in my opinion it just feels more proper. So this massive rewrite looks as follows:

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

The RewriteCond uses a regular expression to distinguish which domain is initially being used. ^ means we start our matching from the beginning of the string. (www\.)? means their may or may not be a "www." at the beginning (? means may or may not exist). Finally we just state our domain name and stating [NC] for not case sensitive. Considering this Rewrite Condition is met we apply the RewriteRule. If not escaped with a "\", the "." is a wildcard, and "" means 0 or more; so . implies 0 or more characters. Now the tricky part is to pay close attention to all sets of parenthesis in that regular expression, and the $1 in our redirect url. Each set of parentasis create a "capture", which can be accessed by a $. That being said if I had three sets of parentasis the first captured element could be accessed by $1, the second capture by $2, etc. This is how we capture any url from the old domain and append it to our new domain. Hope this helps someone else out, or if you have any other possibilities don't be shy, please share!