Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

apache - .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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...