如何使用反向代理将所有请求正确地重定向到 Nginx 中的非 www

如何使用反向代理将所有请求正确地重定向到 Nginx 中的非 www

我有一个由 nginx 内部的反向代理提供服务的 React 网站。除此之外,我还拥有 SSL。Certbot 正在处理从 http 到 https 的重定向。我还想设置从 www 到非 www 的重定向。我想知道正确的方法是什么?

我的配置如下:

server {
    server_name example.com www.example.com;
    location / {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto http;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Host $remote_addr;
        proxy_cache_bypass $http_upgrade;
        proxy_hide_header X-Powered-By;
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "origin-when-cross-origin" always;
    }
    error_page 502 /index.html;
    location /index.html {
        root /var/www/subdomains/service;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = www.example.com) {
        return 301 https://example.com$request_uri;
    }

    server_name example.com;
    listen 80;
    return 404; # managed by Certbot
}

请注意,这两个页面(www 和非 www)目前都可以使用。我只是想避免重复链接,所以我只想要非 www 版本。

答案1

将您的 SSL 服务器块拆分为两部分:

server {
    server_name www.example.com;
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    return 301 https://example.com$request_uri;
}
server {
    server_name example.com;
    ... # your main config here
}

相关内容