域名解析与 HTTPS 配置

更新于 2026年8月21日

适用人群:Node 应用已通过 Nginx 反代、要配好域名与 HTTPS 的开发者。

核心概念

TLS 在 Nginx 终结

证书装在 Nginx 上,用户到 Nginx 走 HTTPS,Nginx 到本机 Node 走普通 HTTP(同机回环,安全)。Node 应用无需自己处理证书。

让应用知道是 HTTPS

因为 TLS 在 Nginx 终结,Node 收到的是 http。要让应用正确生成 https 链接、判断协议,需透传 X-Forwarded-Proto 并在框架里信任代理(Next/Nuxt 通常能识别标准转发头)。

操作步骤

  1. 步骤 1解析域名

    A 记录指向服务器公网 IP,@ 与 www 各一条。

  2. 步骤 2申请证书

    certbot --nginx 自动为域名申请 Let's Encrypt 证书并写入 Nginx。

  3. 步骤 3配 HTTPS + 跳转

    443 server 块引用证书,80 端口 301 跳 HTTPS;反代 location 保持不变。

  4. 步骤 4透传协议

    确认反代已加 X-Forwarded-Proto $scheme,应用据此识别 https。

  5. 步骤 5验证续期

    certbot renew --dry-run 验证自动续期正常。

实际示例

server {
    listen 443 ssl;
    server_name example.com www.example.com;
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }

常见错误

  • ⚠️没透传 X-Forwarded-Proto,应用把 https 请求当成 http,生成的绝对链接、回调地址错成 http
  • ⚠️在 Node 里又配了一套证书,与 Nginx 层重复且容易冲突
  • ⚠️只配了 443 没做 80→443 跳转,用户走 http 明文访问
  • ⚠️证书没自动续期

对应工具

常见问题

证书装在 Nginx 还是 Node?
装在 Nginx,由它终结 TLS;Node 只在本机收 http 反代请求,无需自己管证书。
应用生成的链接是 http 不是 https?
在反代加 X-Forwarded-Proto $scheme,并让框架信任代理头,应用就能正确识别为 https。

相关教程

相关文章

官方资料来源