nginx将所有通配符子域重写为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
与
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/
是的,这肯定有效.