Create a Redirect in Drupal's .htaccess For The Base URL

Patrick

I recently needed to redirect a client's traffic from their old URL to a new one. In this case, they wanted any traffic going to plain example1.com to go to example2.com/blog and all other traffic to go to example2.com/[equivalent URI] (e.g., example1.com/about --> example2.com/about).

To do this, I messed around with rewrite rules and conditions for a while, until I decided on what seems to be a fairly straight forward solution:

# Redirect example1.com to example2.com/blog
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^$ http://example2.com/blog [r=301,L]
# Redirect example1.com/example to example2.com/example
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^(.*)$ http://example2.com/$1 [r=301,L]

The key here is "RewriteRule ^$", which looks for an empty pattern for the request URI, that is, the portion of the URL AFTER http:// and the host name (e.g., http://example.com). That way, if a person just enters in "http://example.org" it will redirect them to http://example2.org/blog. The second section of the code is there to redirect all other traffic to a similar page on example2.com (taking everything matched after http://example.com and slapping it in after http://example2.org.

Pretty simple and so far it's working well. In my case, I also added a similar bit of code to redirect "www." traffic as well per Drupal's default .htaccess directions.