ssl - NGINX 配置不将非 www 重定向到 www

标签 ssl nginx nginx-config

我有一个 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 -> 工作正常

有什么建议吗?

最佳答案

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

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;
   }
}

关于ssl - NGINX 配置不将非 www 重定向到 www,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52088703/

相关文章:

nginx - 如何配置 Nginx 在 404ing 之前尝试两个上游?

ubuntu - 恢复完整的nginx配置

php - 允许 php 值只在子目录中工作

ssl - Heroku 更新 SSL 证书

google-chrome - 关于不信任 Symantec 证书的 Chrome 警告发生了什么?

php - SQL Buddy + https(ssl) + nginx 无法登录

nginx lua redis cookie 未设置

java - 自定义 Java 生产者中的 Kafka SSL 握手失败

macos - 在 macOS 中将自签名证书添加为受信任的证书无法正常工作

nginx 在不使用 lua 模块的情况下匹配请求体