如何让nginx从www重定向到非www域?

Jau*_* Ho 9 website nginx web-hosting web-server web

假设我想从 www.example.com 重定向到 example.com 并且我想使用 nginx 来做到这一点。我环顾四周,没有看到任何关于此的好的文档,所以我想我会问并回答我自己的问题。

小智 7

我也在 Nginx wiki 和其他博客上查看了这个,性能方面的最佳方法是执行以下操作:

使用 nginx(在撰写本文时为 1.0.12 版)从 www.example.com 重定向到 example.com。

server {
  server_name www.example.com;
  rewrite ^ $scheme://example.com$request_uri permanent; 
  # permanent sends a 301 redirect whereas redirect sends a 302 temporary redirect
  # $scheme uses http or https accordingly
}

server {
  server_name example.com;
  # the rest of your config goes here
}
Run Code Online (Sandbox Code Playgroud)

当请求到达 example.com 时,不使用 if 语句来提高性能。并且它使用 $request_uri 而不是必须创建一个 $1 匹配,从而对重写征税(请参阅 Nginx 常见陷阱页面)。

资料来源:


小智 5

请访问以下问题:/sf/answers/821335441/

来自更好的答案:

实际上你甚至不需要重写。

server {
    #listen 80 is default
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    #listen 80 is default
    server_name example.com;
    ## here goes the rest of your conf...
}
Run Code Online (Sandbox Code Playgroud)

因为我的答案得到了越来越多的支持,但上述情况也是如此。你不应该rewrite在这种情况下使用 a 。为什么?因为nginx要处理并开始搜索。如果你使用return(应该在任何 nginx 版本中都可用),它会直接停止执行。这在任何情况下都是首选。


Jau*_* Ho 4

经过一番挖掘和一些失误之后,这是解决方案。我遇到的问题是确保使用“ http://example.com $uri”。在 $uri 前面插入 / 会导致重定向到http://example.com//

  server {
    listen 80;
    server_name www.example.com;
    rewrite ^ http://example.com$uri permanent;
  }

  # the server directive is nginx's virtual host directive.
  server {
    # port to listen on. Can also be set to an IP:PORT
    listen 80;

    # Set the charset
    charset utf-8;

    # Set the max size for file uploads to 10Mb
    client_max_body_size 10M;

    # sets the domain[s] that this vhost server requests for
    server_name example.com;

    # doc root
    root /var/www/example.com;

    # vhost specific access log
    access_log  /var/log/nginx_access.log  main;


    # set vary to off to avoid duplicate headers
    gzip off;
    gzip_vary off;


    # Set image format types to expire in a very long time
    location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
        access_log off;
        expires max;
    }

    # Set css and js to expire in a very long time
    location ~* ^.+\.(css|js)$ {
        access_log off;
        expires max;
    }

    # Catchall for everything else
    location / {
      root /var/www/example.com;
      access_log off;

      index index.html;
      expires 1d;

      if (-f $request_filename) {
        break;
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)