将 Nginx 配置为应用的反向代理,并通过免费的 Let's Encrypt 证书自动启用 HTTPS。

本指南假设你已经安装了 Nginx(参见 Nginx 安装指南),并且已有域名解析到你的 VPS IP。

  1. 安装 Certbot 和 Nginx 插件:
    apt update && apt install certbot python3-certbot-nginx
  2. /etc/nginx/sites-available/myapp 创建站点配置。请将 yourdomain.com 和代理端口替换为你自己的值:
    server {
        listen 80;
        server_name yourdomain.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
  3. 启用站点并重载 Nginx:
    ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
    nginx -t && systemctl reload nginx
  4. 在门户上游防火墙和本地同时放行 80 和 443 端口:
    ufw allow "Nginx Full"
  5. 申请免费的 SSL 证书:
    certbot --nginx -d yourdomain.com
    Certbot 会自动改写你的 Nginx 配置,以处理 HTTPS 以及从 HTTP 到 HTTPS 的跳转。
  6. 确认自动续期已启用:
    systemctl status certbot.timer
    Certbot 会在证书到期前自动续期,无需手动操作。

多个域名:为每个新增站点重复第 2 到第 5 步,并为每个域名使用独立的配置文件,各自获得自己的证书。

这篇指南对你有帮助吗?

感谢你的反馈!