nginx certbot 证书 www 和非 www

Mat*_*ren 3 ssl nginx https lets-encrypt certbot

我还没有真正了解如何使用 certbot 为 nginx 创建(工作)证书。

我的网站启用现在看起来像这样:

首先,使用 SSL 阻止 www 域。所有 SSL 的东西都是由 certbot 创建的。

server {
root …
index … 
server_name www.doman.com
listen 443 ssl;
ssl_certificate …
ssl_certificate_key …
include …
ssl_dhparam … 
}
Run Code Online (Sandbox Code Playgroud)

在此之后,为 www 和非 www 从端口 80 重定向到端口 443。第一部分——if 语句——是由 certbot 创建的,而不是我。

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

listen *:80;
server_name domain.com www.example.com;
return 301 https://www.example.com$request_uri;
Run Code Online (Sandbox Code Playgroud)

}

最后,一个没有 www 的 443 块。我希望这重定向到 www。

server {
listen 443;
server_name www.domain.com
return 301 https://www.example.com$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

这对于带有 www 的域来说效果很好。但是,如果没有 www,我会收到“无法访问此站点”。即使我尝试使用 http 而不是 https。

我他妈的在哪里?我的猜测是,对于非 www 使用 443 的第三个块也需要 SSL 证书。但是我使用 certbots 自动创建,它没有添加任何内容。

Mic*_*ton 8

我不允许 certbot 创建我的 Web 服务器配置。坦率地说,我不相信它会做对,因为它已经在做一些效率不高的实践。

所以我得到了证书certbot certonly --webroot -w /var/www -d hostname -d hostname......

我的 nginx 配置如下所示(例如一个域):

server {
    server_name www.yes-www.org yes-www.org;

    access_log off;

    include includes/listen-80;
    include includes/cloudflare;
    include includes/letsencrypt;

    location / {
        return 301 https://$host$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于端口 80,我只是提供两个主机名并无条件地重定向到 https 和 www。

server {
    server_name yes-www.org;

    access_log off;

    ssl_certificate /etc/letsencrypt/live/www.yes-www.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.yes-www.org/privkey.pem;

    include includes/listen-443;
    include includes/cloudflare;
    include includes/ssl;
    include includes/hsts;
    include includes/letsencrypt;

    location / {
        return 301 https://www.yes-www.org$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于端口 443 非 www,我只是无条件地重定向到 www。

server {
    server_name www.yes-www.org;

    root /srv/www/yes-www.org;

    access_log /var/log/nginx/yes-www.org-access.log nginx;
    access_log /var/log/nginx/cache.log cache;
    error_log /var/log/nginx/yes-www.org-error.log;

    ssl_certificate /etc/letsencrypt/live/www.yes-www.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.yes-www.org/privkey.pem;

    include includes/listen-443;
    include includes/cloudflare;
    include includes/letsencrypt;
    include includes/ssl;
    include includes/hsts;
    include includes/favicon;
    include includes/wordpress;
    include includes/php;
    include /srv/www/yes-www.org/nginx.conf;

    location ~ /\.(ht|git) {
        deny all;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后在这里,我为一个网站提供服务。

注意内容/etc/nginx/includes/letsencrypt是:

location /.well-known/acme-challenge/ {
    root /var/www;
    try_files $uri =404;
}
Run Code Online (Sandbox Code Playgroud)

这使得certbot certonly上述工作。