Nginx将非www前缀的域重写为www前缀的域 [英] Nginx rewrite non-www-prefixed domain to www-prefixed domain
问题描述
我看到Nginx HttpRewriteModule文档提供了一个示例,用于将www前缀的域重写为非www前缀的域:
I see the Nginx HttpRewriteModule documentation has an example to rewrite a www-prefixed domain to a non-www-prefixed domain:
if ($host ~* www\.(.*)) {
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1 permanent; # $1 contains '/foo', not 'www.mydomain.com/foo'
}
我该如何反向操作-将非www前缀的域重写为www前缀的域?我以为也许可以做以下事情,但Nginx不喜欢嵌套的if语句.
How can I do the reverse-- rewrite a non-www-prefixed domain to a www-prefixed domain? I thought maybe I could do something like the following but Nginx doesn't like the nested if statement.
if ($host !~* ^www\.) { # check if host doesn't start with www.
if ($host ~* ([a-z0-9]+\.[a-z0-9]+)) { # check host is of the form xxx.xxx (i.e. no subdomain)
set $host_with_www www.$1;
rewrite ^(.*)$ http://$host_with_www$1 permanent;
}
}
我也希望它适用于任何域名,而无需明确告诉Nginx重写domain1.com-> www.domain1.com,domain2.com-> www.domain2.com等,因为我有很多要重写的域.
Also I wanted this to work for any domain name without explicitly telling Nginx to rewrite domain1.com -> www.domain1.com, domain2.com -> www.domain2.com, etc. since I have a large number of domains to rewrite.
推荐答案
好吧,我猜我真的不需要外部的"if"语句,因为无论如何我只检查xxx.xxx形式的域.以下内容对我有用,尽管它并不可靠.让我知道是否有更好的解决方案.
Well I guess I don't really need the outer "if" statement since I'm only checking for domains of the form xxx.xxx anyways. The following works for me, though it's not robust. Let me know if there is a better solution.
if ($host ~* ^([a-z0-9\-]+\.(com|net|org))$) {
set $host_with_www www.$1;
rewrite ^(.*)$ http://$host_with_www$1 permanent;
}
在正则表达式中添加了连字符,因为它是主机名中的有效字符.
Added hyphen to the regular expression since it is a valid character in a hostname.
这篇关于Nginx将非www前缀的域重写为www前缀的域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!