Reza Karami
Reza Karami

Reputation: 515

.htaccess - Redirect subdomain and path to same subdomain and path on another domain

I have looked far and wide for a solution but haven't been able to find one that resolved my issue.

I am trying to implement a 301 redirect that would redirect the user to another domain, with the same subdomain and path as the one they requested.

i.e. if they land on sub1.domain1.com/page.php they get redirected to sub1.domain2.com/page.php. The redirect should catch ANY subdomain.

I have set the AllowOverride to All on the /var/www/html directory and tried the following but with no luck:

#RewriteEngine On
#RewriteCond %{HTTP_HOST} (.*).domain1.com
#RewriteRule (.*) http://%1.domain2.com/$1 [R=301,QSA,L]

Any help is much appreciated. Thanks in advance!

Upvotes: 0

Views: 1225

Answers (1)

jerdiggity
jerdiggity

Reputation: 3675

As w3d mentioned in a comment, the # signs need to be removed from the beginning of each line in order for the rules to take effect.

Also, you should update this:

RewriteCond %{HTTP_HOST} (.*).domain1.com

... so that it now looks something like this:

RewriteCond %{HTTP_HOST} ^(.+)\.domain1\.com$

The ^ sign signifies the beginning of a value, and the $ signifies the end of a value.

The reason for replacing (.*) with (.+) is because theoretically you're telling your server that .domain1.com is a valid domain name when you use (.*) (when in fact there should at least be once character before the first dot).

The reason for the backslashes is to escape the dots inside the RewriteCond. See this page for more info on rewrite conditions and rules.

Ultimately you might end up with something like this:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.domain1\.com$
RewriteRule ^(.*)$ http://%1.domain2.com/$1 [R=301,QSA,L]

Upvotes: 1

Related Questions