05/07/08
.htaccess redirect based on requested domain
I often use the following .htaccess / mod_rewrite solution to redirect domain names based on the requested domain. The reasons for this are many. Most recent example for me is I had a single site with 5 alias domains but software licensed for only one. Even though I had the alias domains set up on the server it still did not satisfy the license. Add the line below to htaccess and now no matter which of the 5 domains are written in they are re-written to the one with the licence (need to duplicate for each domain). The license is valid since its all the same physical website and everyone is happy. Brilliant!
I am sure there is a more eloquent way of accomplishing this with mod_rewrite – but this gets the job done!
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?yourdomain\.com [NC]
RewriteRule ^(.*)$ http://otherdomain.com/$1 [R=301,L]
Can also be used to redirect to a landing page based on the requested domain:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com
Rewriterule ^(.*)$ http://www.any-domain.com/landing-page.html [L]
Have a better solution? I’m no mod_rewrite guru so comments are always welcome!
htaccess redirect is the most SEO friendly way to redirect URLs. However, most people tend to forget that it’s also the most user friendly method. This allows instant redirects since the web server reads the htaccess file before showing the web page. This prevents you from losing visitors due to long web page loading times. Great Article!