在 CentOS 上给 Node.js 配置 SSL(HTTPS),通常有两种常见方式:
你需要:
cert.pem(或 fullchain.pem)key.pem如果是 Let’s Encrypt:
/etc/letsencrypt/live/yourdomain.com/fullchain.pem
/etc/letsencrypt/live/yourdomain.com/privkey.pem
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('HTTPS OK');
});
const options = {
cert: fs.readFileSync('/path/to/fullchain.pem'),
key: fs.readFileSync('/path/to/privkey.pem')
};
https.createServer(options, app).listen(443, () => {
console.log('HTTPS server running on port 443');
});
⚠️ Node.js 监听 443 需要 root 权限
yum install nginx -y
systemctl enable nginx
systemctl start nginx
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
app.listen(3000, () => {
console.log('Node.js running on 3000');
});
yum install certbot -y
certbot certonly --nginx -d yourdomain.com
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
云服务器还需在安全组开放 443
| 场景 | 推荐方式 |
|---|---|
| 学习 / 内网 | Node.js 直接 HTTPS |
| 生产环境 | Nginx + Node.js |
| 高并发 | Nginx 必备 |
如果你愿意,可以告诉我:
我可以给你 完整可复制配置。