【问题标题】:NGINX configurations not redirecting non-www to wwwNGINX 配置不会将非 www 重定向到 www
【发布时间】:2018-08-30 16:02:25
【问题描述】:

我有一个 NodeJS 应用程序在 AWS EC2 实例上托管的 Ubuntu 16 服务器上的 3000 端口上运行。我希望 NGINX 将以下每个地址重定向到 https://www.example.com:

  1. http://example.com
  2. http://www.example.com
  3. https://example.com

为此,我将/etc/nginx/sites-available/default 文件配置如下:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    location / {
        # Redirect any http requests to https
        return 301 https://www.$server_name$request_uri;
     }
     location ~* \.(?:ico|svg|woff|woff2|ttf|otf|css|js|gif|jpe?g|png)$ {
        proxy_pass http://127.0.0.1:3000;
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";
     }
}

# Settings for a TLS enabled server
server {
        listen 443 ssl http2;
        listen [::]:443 ssl;
        server_name  www.example.com;

        ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
        ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";

        # Automatically route HTTP to HTTPS
        add_header Strict-Transport-Security "max-age=31536000";

        include /etc/nginx/default.d/*.conf;

        location / {
            proxy_pass http://127.0.0.1:3000;
       }
   }

但是,这似乎只是部分起作用:

  1. http://example.com -> 转到 https://example.com 而不是 https://www.example.com
  2. http://www.example.com -> 转到 https://example.com 而不是 https://www.example.com
  3. https://example.com -> 转到 https://example.com 而不是 https://www.example.com
  4. https://www.example.com -> 工作正常

有什么建议吗?

【问题讨论】:

  • 您没有测试用例 (3) 的实现,结合您的 HSTS 标头是测试用例 (1) 似乎失败的原因。

标签: ssl nginx nginx-config


【解决方案1】:

对于要重定向的每个案例,您都应该有一个服务器块:

server {
  listen 80;
  listen [::]:80;
  server_name example.com;
  return 301 https://www.example.com$request_uri;
}
server {
  listen 80;
  listen [::]:80;
  server_name www.example.com;
  return 301 https://www.example.com$request_uri;
}

# Settings for a TLS enabled server
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name  www.example.com;

    ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
    ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";

    # Automatically route HTTP to HTTPS
    add_header Strict-Transport-Security "max-age=31536000";

    include /etc/nginx/default.d/*.conf;

    location / {
        proxy_pass http://127.0.0.1:3000;
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-23
    • 2020-12-31
    • 2017-03-10
    • 2018-04-22
    • 2018-02-02
    相关资源
    最近更新 更多