ssl-guides 2026-12-02 ⏱ 1 min read

为 Node.js 配置 SSL:HTTPS 服务

为 Node.js 配置 SSL:HTTPS 服务

要为 Node.js 添加 SSL,使用内置的 https 模块,配上证书和对应的私钥,大约十行代码。Node.js 自己就能讲 HTTPS。更难的问题是在哪里终止 TLS、如何在不使用 root 的情况下占用 443 端口,以及如何取到续期后的证书。

Node.js 的 SSL,方式 1:在应用中终止 TLS

先取得证书。如果有域名指向这台服务器,Let's Encrypt 的免费证书就可以;见用 Certbot 获取免费 SSL 证书。Certbot 把文件写到 /etc/letsencrypt/live/example.com/,下面的代码读取 /etc/ssl/app/ 中的副本,好让 Node 进程能打开它们。然后创建服务器:

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('/etc/ssl/app/privkey.pem'),
  cert: fs.readFileSync('/etc/ssl/app/fullchain.pem'),
  minVersion: 'TLSv1.2',
};

https.createServer(options, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('secure hello\n');
}).listen(8443);

fullchain.pem 选项要用 cert,不能只用叶子证书。如果漏掉中间证书,桌面浏览器通常还能应付,但很多 API 客户端和移动应用会报告证书链不完整。同样的代码也适用于 Express:把 app 传给 https.createServer(options, app)。

在 443 端口上运行

Linux 上 1024 以下的端口是特权端口。为了占用 443 而让 Node 以 root 运行是坏主意。更好的选择:

  • 监听 8443,用防火墙把 443 转发过去。
  • 只授予绑定能力:sudo setcap 'cap_net_bind_service=+ep' $(which node)。
  • 在 443 上放反向代理,让 Node 留在 localhost(方式 2)。

把 HTTP 跳转到 HTTPS

在 80 端口再跑一个小服务器,发送永久重定向:

require('http').createServer((req, res) => {
  const host = (req.headers.host || '').split(':')[0];
  res.writeHead(301, { Location: 'https://' + host + req.url });
  res.end();
}).listen(80);

不重启即可重载证书

Let's Encrypt 证书目前有效期 90 天,从 10 February 2027 起 64 天,从 16 February 2028 起 45 天(Let's Encrypt 公告),Certbot 会原地续期。Node 只在启动时读取文件,所以会一直提供旧证书直到重启。用 setSecureContext 可以避免重启(Node.js TLS 文档):

const server = https.createServer(options, handler);

function reload() {
  server.setSecureContext({
    key: fs.readFileSync('/etc/ssl/app/privkey.pem'),
    cert: fs.readFileSync('/etc/ssl/app/fullchain.pem'),
  });
}
process.on('SIGHUP', reload);

然后添加 Certbot deploy hook,复制新文件并向进程发送 SIGHUP。钩子细节见用 Certbot 自动续期 SSL。不要为了让 Node 能打开 /etc/letsencrypt/live 就把该目录设成所有人可读;把文件复制到服务账号拥有的位置。

Node.js 的 SSL,方式 2:在反向代理终止 TLS

生产环境中的 Node 应用大多位于 Nginx、Caddy、HAProxy 或云负载均衡之后。代理负责证书、续期和协议设置,Node 在 127.0.0.1 上提供普通 HTTP。此时你的代码需要信任转发来的协议。在 Express 中:

const app = require('express')();
app.set('trust proxy', 1);   // trust the first proxy hop

app.use((req, res, next) => {
  if (req.secure) return next();
  res.redirect(301, 'https://' + req.headers.host + req.url);
});

只有在前面确实有代理时才设置 trust proxy,否则客户端可以伪造 X-Forwarded-Proto。代理配置见为反向代理配置免费 SSL。协议选择方面,网站最佳 TLS 配置是很好的基准。

Node 的出站 HTTPS

Node 默认校验服务器证书。不要用 NODE_TLS_REJECT_UNAUTHORIZED=0 或 rejectUnauthorized: false 来消掉错误;那会关掉让 TLS 有用的那项检查。如果涉及私有 CA,把 NODE_EXTRA_CA_CERTS 指向它的证书文件。

验证结果

命令显示什么
curl -vI https://example.com握手、协议和证书主题
openssl s_client -connect example.com:443服务器发送的完整证书链
curl -I http://example.com301 跳转是否生效

OpenSSL 检查的完整讲解见用 OpenSSL 测试 SSL 配置。

常见错误

  • 只提供 cert.pem 而没有中间证书链,会让部分客户端失败。
  • 为了让应用够到 443 端口而整段以 root 运行。
  • 把 privkey.pem 提交到仓库。密钥要远离版本控制和容器镜像。
  • 忘了磁盘上的续期在 Node 重载上下文或重启之前毫无作用。
  • 为了绕开开发阶段的错误而关掉出站调用的证书校验,然后就这样上线。

这些在上线前的简短评审中都很容易发现,修起来也都不超过几行。

相关阅读:nginx 上的免费 SSL、续期免费 SSL 证书 和 API 的 mTLS。

常见问题

如果前面有 Nginx,Node.js 还需要证书吗?

不需要。让代理终止 TLS,Node 在 127.0.0.1 上提供普通 HTTP,然后告诉应用信任转发来的协议。

为什么续期后 Node 还在提供旧证书?

它在启动时读取了文件。用 setSecureContext 重载上下文,或通过 Certbot deploy hook 重启进程。

Node.js 能在不用 root 的情况下占用 443 端口吗?

在 Linux 上不能直接做到。在前面放代理或负载均衡,或者把该能力授予这个二进制文件。

🔒 Test Your Website SSL Certificate Now
Run Free SSL Check →

✅ Post-Installation Verification & SEO Checklist

After applying the steps above, run through this 5-point checklist to prevent browser warnings and protect your Google SEO rankings:

  • Verify full CA chain trust and TLS 1.3 support using our Live SSL Checker.
  • Scan for Mixed Content HTTP links and check HSTS/CSP headers on Security Headers Checker.
  • Enforce a permanent 301 HTTP-to-HTTPS redirect with our HTTPS Redirect Generator.
  • Confirm both root and www versions resolve cleanly to one canonical HTTPS URL.
  • Verify your HTTPS property and sitemap.xml inside Google Search Console and Bing Webmaster Tools.
Technically Reviewed by TryFreeSSL Security Team
Last updated: 2026-12-05
About Us →

免费 SSL 证书签发、在线 SSL 检测与 CSR 生成器

无需复杂服务器配置,60 秒快速获取 Let's Encrypt 与 Buypass 信任的 HTTPS 证书。

Related Articles

🤖 TryFreeSSL AI Assistant