Redirecting domains with mod_rewrite

Sometimes you need to move a site from one domain to another, or you might have one or more domains that you want to all forward to another, such as variations on your primary domain. For example, your main site might be “www.example.com” and you want anyone who types in or follows a link to “www.example.org” or “www.example.net” to go to the .com site. Apache web servers use a module called mod_rewrite to rewrite URL’s on the fly. Here is the code that will do this for our examples:

RewriteCond %{HTTP_HOST} ^(www\.)?example\.org [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?example\.net [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

This code resides in the .htaccess file in the folder to which the domains point. The first two lines establish the conditions (RewriteCond) when the rule in the third line (RewriteRule) should be applied. The conditions use regular expressions to specify that the rule should be applied to any URL’s that look like www.example.org or www.example.net, and even if the www is left off. The “NC” means to ignore the case of the text, and the “OR” in the first line says that either condition is sufficient apply the rule. The rule specifies the new domain to use, and that the redirect should use a return code of 301, which corresponds to a permanent move.

This technique is a powerful and efficient way to “move” domains while preserving the SEO benefits (in-bound links) of a domain that is no longer being used.

Bookmark and Share