Nginx 将非 WWW 重定向到 WWW / SSL certbot

Nginx 将非 WWW 重定向到 WWW / SSL certbot

我一直在想办法如何将非 WWW 域的请求重定向到 WWW 域。这是 HTTPS.conf 文件:

server {
    server_name domain.com *.domain.com;
    return 302 https://$host$request_uri;
}


 server {
    listen 443 ssl default_server;
    server_name www.domain.com;

    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
}

根据配置,它应该可以正常工作。因为所有非 WWW 域都应该重定向,但事实并非如此。出于测试目的,我已将 301 更改为 302。这些是我运行 nginx -t 时收到的错误

nginx: [warn] conflicting server name "domain.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "domain.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "*.domain.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "www.domain.com" on 0.0.0.0:443, ignored

这是管理证书的 HTTP.conf 文件。

server {
    server_name www.domain.com domain.com;

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

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


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

    listen 80 default_server;
    server_name www.domain.com domain.com;
    return 404; # managed by Certbot
}

我确信问题出在 certbot 生成的最后几行 if 上。但如果我更改它们/从 port80 服务器块中删除 domain.com,结果会是“SSL 证书无效”。可能是因为重定向。这里的因素太多了,我无法独自找出解决方案。我对 http 到 https 重定向没有问题。

答案1

这可能是答案吗?我在自己的服务器上使用过几次。 https://stackoverflow.com/questions/10294481/how-to-redirect-a-url-in-nginx

答案2

我发现答案比我最初想象的要复杂一些。主要问题是我同时拥有 HTTP.conf 和 HTTPS.conf。我删除了 HTTPS.conf,因为所有 https 请求都在 http.conf 中处理。我移动了重定向。我编辑了 http.conf,最后得到如下内容:

server {
    server_name domain.com www.domain.com;
    return 301 https://www.$host$request_uri;
}

server {
    server_name www.domain.com;

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

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


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

    #listen 80 default_server;
    #server_name www.domain.com domain.com;
    #return 404; # managed by Certbot
}

它似乎无法在我的主电脑上运行(即使使用隐身模式),但它可以在重定向检查工具和其他设备上运行。

相关内容