nginx 将所有通配符子域重写为 www.site.com [英] nginx rewrite all wildcard subdomains to www.site.com
问题描述
使用 nginx,我想将 example.com
的所有子域重定向到 www.example.com
.
Using nginx, I want to redirect all subdomains of example.com
to www.example.com
.
我在这里看到重定向将非 www 重定向到 www 或反之亦然,但我也希望 www2.site.com blabla.site.com
被重定向.我有一个域的通配符 dns.
I have seen redirects here to redirect non-www to www or vise versa, but I also want www2.site.com blabla.site.com
to be redirected.
I have a wildcard dns for the domain.
对于 apache,这可以通过以下方式轻松完成:
For apache this can be done easily with following:
RewriteCond %{HTTP_HOST} !www.example.com [NC]
RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]
以下似乎有效,但根据 ifisevil 页面,不建议这样做.
The below seem to work, but it is not recommended according to the ifisevil page.
if ($http_host !~ "www.site.com"){
rewrite ^(.*)$ http://www.example.com$request_uri redirect;
}
推荐答案
在 nginx 中做到这一点的最佳方法是结合两个服务器块:
The best way to do this in nginx is with a combination of two server blocks:
server {
server_name *.example.org;
return 301 $scheme://example.org$request_uri;
}
server {
server_name www.example.org;
#add in further directives to serve your content
}
我已经在我的笔记本电脑上测试过这个,因为你报告它不起作用.我在本地得到以下结果(在将 www2.test.localhost
和 www.test.localhost
添加到我的 /etc/hosts
之后,以及nginx 配置位,并重新加载 nginx):
I have tested this on my laptop, since you reported it not working. I get the following result locally (after adding www2.test.localhost
and www.test.localhost
to my /etc/hosts
, along with the nginx config bit, and reloading nginx):
$ curl --head www2.test.localhost
HTTP/1.1 301 Moved Permanently
Server: nginx/1.2.6
Date: Thu, 07 Mar 2013 12:29:32 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://www.test.localhost/
所以是的,这绝对有效.
So yes, this definitely works.
这篇关于nginx 将所有通配符子域重写为 www.site.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!