nginx将所有通配符子域重写为www.site.com

use*_*308 13 nginx url-rewriting

使用nginx的,我想重定向的所有子域example.comwww.example.com.

我在这里看到重定向将非www重定向到www或反之亦然,但我也希望www2.site.com blabla.site.com被重定向.我有域的通配符dns.

对于apache,可以通过以下方式轻松完成:

RewriteCond %{HTTP_HOST} !www.example.com [NC]
RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]
Run Code Online (Sandbox Code Playgroud)

以下似乎工作,但不建议根据ifisevil页面.

if ($http_host !~ "www.site.com"){
    rewrite ^(.*)$ http://www.example.com$request_uri redirect;
}
Run Code Online (Sandbox Code Playgroud)

cob*_*aco 21

在nginx中执行此操作的最佳方法是使用两个服务器块的组合:

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
}
Run Code Online (Sandbox Code Playgroud)

我已经在笔记本电脑上测试了这个,因为你报告它不起作用.我在本地得到以下结果(在添加www2.test.localhostwww.test.localhost我的/etc/hosts,以及nginx配置位,并重新加载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/
Run Code Online (Sandbox Code Playgroud)

所以是的,这绝对有效.

  • 没有:你有一个**.example.com`的*通配符*服务器块和一个*完全匹配*的服务器块,用于"www.example.com".因此,www.example.com不会被重写,因为它是在第二个块而不是第一个块中处理的.server_name的匹配顺序为:1 - 确切名称,2 - 以*开头的最长匹配,3 - 以*,4 - 第一个正则表达式匹配结束的最长匹配(如http://nginx.org/en/docs/中所述) HTTP/ngx_http_core_module.html#服务器名) (4认同)
  • 请不要使用`rewrite ^ permanent`而不是简单的`return`.执行正则表达式(即使这么简单的一个`^`)只是在这种情况下浪费CPU. (3认同)

VBa*_*art 13

server {
    server_name .example.com;
    return 301 http://www.example.com$request_uri;
}

server {
    server_name www.example.com;
    [...]
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • 我试过.site.com根据手册同时捕获*.site.com和site.com (2认同)