我有一个testing服务器(webtest.example.com)和一个在线服务器(www.example.com)。
我也有example.org,example.net等我希望那些redirect到example.com。 我也想要任何非www条目redirect到www。
基本上,我只想知道是否有更高效(即更less线路)的方式来处理这个问题?
RewriteCond %{HTTP_HOST} !^www\.example\.com$ RewriteCond %{HTTP_HOST} !^webtest\.example RewriteRule ^(.*)$ http://www.example.com%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^webtest\.example\.com$ RewriteCond %{HTTP_HOST} ^webtest\.example RewriteRule ^(.*)$ http://webtest.example.com%{REQUEST_URI} [L,R=301]
似乎也许会有一种方法将2个块合并成一个块。
从做你想做的规则开始,然后把它们组合起来。 在这个问题中,你有3个要求和规则,只包括其中两个 – 有一个规则丢失。
一个关键的技巧是编写使用肯定匹配(以foo开头)的规则,而不是否定匹配(除了foo之外的任何内容),否则需要排除,如果将来添加到规则集中,事情很容易中断。
在这种情况下有很多例子 :
RewriteCond %{HTTP_HOST} ^example RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301,L]
无论是example.com , example.net还是example.org – 它们都以示例开头 – 匹配no-www域请求并redirect到www.example.com
为此,请使用负面预测来排除www.example.com :
RewriteCond %{HTTP_HOST} ^www\.example\.(?!com)$ RewriteRule ^ http://www.example.com%{REQUEST_URI} [L,R=301]
即匹配以www.example开头的任何主机,不以.com结尾
同样,使用负向前视,可以将其标准化:
# capture the subdomain, and match hosts that don't end with .com RewriteCond %{HTTP_HOST} ^webtest\.example\.(?!com) RewriteRule ^ http://webtest.example.com%{REQUEST_URI} [L,R=301]
即匹配任何以webtest.example开始的主机,不以.com结尾
子域上的可以是:
RewriteCond %{HTTP_HOST} ^(www|webtest)\.example\.(?!com) RewriteRule ^ http://%1.example.com%{REQUEST_URI} [L,R=301]
然而,第一个不容易被包含在这里(至less,我想不出一个微不足道的方法)。
最终的结果是:
# Redirect no-www requests to www.example.com RewriteCond %{HTTP_HOST} ^example RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301,L] # Redirect requests on the wrong tld to .com RewriteCond %{HTTP_HOST} ^(www|webtest)\.example\.(?!com) RewriteRule ^ http://%1.example.com%{REQUEST_URI} [L,R=301]