温馨提示×

linux nodejs如何配置https

小樊
45
2026-10-16 00:22:22
栏目: 编程语言

在 Linux 上使用 Node.js 配置 HTTPS,核心是为 Node.js 服务提供 SSL/TLS 证书(通常是 .crt / .pem 和 .key 文件)。下面从 自签名证书(测试用) 和 正式证书(生产用) 两种场景说明。


一、使用 Node.js 原生 https 模块(最基础方式)

1️⃣ 准备证书

方式一:自签名证书(仅测试)

# 生成私钥
openssl genrsa -out key.pem 2048

# 生成自签名证书
openssl req -new -x509 -key key.pem -out cert.pem -days 365

生成:

  • key.pem(私钥)
  • cert.pem(证书)

2️⃣ Node.js HTTPS 服务示例

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

const options = {
  key: fs.readFileSync('./key.pem'),
  cert: fs.readFileSync('./cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello HTTPS');
}).listen(443, () => {
  console.log('HTTPS server running on port 443');
});

⚠️ 注意:

  • 监听 80 / 443 端口需要 root 权限
  • 推荐使用非 root 用户 + 反向代理(见下文)

二、生产环境推荐方案(Nginx + Node.js)

Node.js 只跑 HTTP,Nginx 处理 HTTPS

1️⃣ Nginx 配置 HTTPS

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

2️⃣ Node.js 只监听本地端口

const http = require('http');

http.createServer((req, res) => {
  res.end('Hello from Node.js');
}).listen(3000);

✅ 优点:

  • 自动续签证书(Let’s Encrypt)
  • 性能更好
  • 更安全

三、使用 Let’s Encrypt 免费证书(推荐)

sudo apt install certbot
sudo certbot certonly --nginx -d example.com

证书位置:

/etc/letsencrypt/live/example.com/
├── fullchain.pem
└── privkey.pem

四、常见问题

❓ 端口权限问题

  • 不要直接用 Node 监听 443
  • 用 Nginx 或 setcap
sudo setcap cap_net_bind_service=+ep /usr/bin/node

❓ 浏览器提示“不安全”

  • 自签名证书正常现象
  • 生产环境必须用受信任 CA

五、总结

场景 推荐方式
本地测试 自签名 + Node https
生产环境 Nginx + Let’s Encrypt
微服务 Node HTTP + 反向代理

如果你有:

  • 使用的框架(Express / Koa / Nest)
  • Linux 发行版
  • 是否用 Docker

我可以给你更具体的配置示例。

0 踩