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

a 夏天 提交于 2019-12-24 21:06:56

问题


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!


回答1:


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]


来源:https://stackoverflow.com/questions/29187992/htaccess-redirect-subdomain-and-path-to-same-subdomain-and-path-on-another-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!