使用.htaccess将非www URL重定向到www [英] Redirecting non-www URL to www using .htaccess
问题描述
我正在使用 Helicon的ISAPI Rewrite 3 ,它基本上可以在IIS中启用.htaccess。我需要将非www网址重定向到www版本,即example.com应该重定向到www.example.com。我从示例中使用了以下规则,但它会影响子域:
I'm using Helicon's ISAPI Rewrite 3, which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:
RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]
这在大多数情况下都有效,但也可以将sub.example.com重定向到www.sub.example.com。我该如何重写以上规则,以使子域不会被重定向?
This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected?
推荐答案
附加以下RewriteCond:
Append the following RewriteCond:
RewriteCond %{HTTP:Host} ^[^.]+\.[a-z]{2,5}$ [NC]
这样,它将仅将规则应用于nondottedsomething.uptofiveletters,如您所见,subdomain.domain.com将不符合条件,因此将不会被重写。
That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.
您可以更改[az] {2,5}以使用更严格的tld匹配正则表达式,并将所有限制域名中允许使用的字符(因为[^。] +比严格的要求更宽松)。
You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.]+ is more permissive than strictly necessary).
总的来说,我认为在这种情况下
All in all I think in this case that wouldn't be necessary.
编辑:sadie在正则表达式上发现了一个缺陷,将其第一部分从[^。]更改为[^。] +
sadie spotted a flaw on the regex, changed the first part of it from [^.] to [^.]+
这篇关于使用.htaccess将非www URL重定向到www的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!