将 SSL(端口 443)添加到 Nginx 反向代理服务器(端口 80)- Nginx 配置文件

Adding an SSL (PORT 443) to an Nginx Reverse Proxy Server (PORT 80) - Nginx Config File

使用 Ubuntu 我使用 Certbot 生成了一个 SSL。这已经自动更新了我的 Nginx 配置文件并添加了一个额外的监听端口。我担心我是否只需要监听一个端口(80 或 443)而不是两个端口,但是我无法找到关于是否需要删除端口 80 的监听的相关信息。请参阅下面的配置文件:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    server_name _;

    location / {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

server {
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my.domain.co.uk/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my.domain.co.uk/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 = my.domain.co.uk) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 ;
    listen [::]:80 ;
    server_name my.domain.co.uk;
    return 404; # managed by Certbot
}

既然 Certbot 已将代码添加到单独的服务器块,我是否需要删除我的初始服务器块在端口 80 上侦听的位置?我有一个旧服务器在使用时一夜之间崩溃的问题,我觉得它与类似于此的 Nginx 配置文件有关。

抱歉,如果这个问题很愚蠢,我对此不是很有经验,并且发现它非常困难,不幸的是。感谢您的任何见解。

您没有包含您想要的内容(例如,哪个应用程序应该在哪些端口上处理请求以及应该对 HTTP 请求执行什么操作)但我假设

  1. 所有 80 端口请求都是 HTTP,所有 443 请求都是 HTTPS。
  2. 您希望将所有 HTTP 请求重定向到 HTTPS
  3. 所有 HTTPS 请求都应传递给节点

如果是这样,这可能就是您真正想要的:

server {
    root /var/www/html;
    server_name my.domain.co.uk;

    location / {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my.domain.co.uk/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my.domain.co.uk/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 = my.domain.co.uk) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80 ;
    listen [::]:80 ;
    server_name my.domain.co.uk;
    return 404; # managed by Certbot
}

第一个服务器块仅处理 HTTPS 请求并将所有请求传递给节点。第二个服务器块仅处理 HTTP 请求并将它们重定向到 HTTPS。