【发布时间】:2010-12-10 09:31:26
【问题描述】:
我看到 Nginx HttpRewriteModule documentation 有一个示例,可以将 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 等,因为我有大量要重写的域。
【问题讨论】:
标签: nginx rewrite url-rewriting