我看到 Nginx HttpRewriteModule 文档有一个将 www 前缀域重写为非 www 前缀域的示例:
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 语句。
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 等,因为我有大量域要重写.