温馨提示×

centos nodejs如何配ssl

小樊
42
2026-09-14 23:22:49
栏目: 云计算

CentOS 上给 Node.js 配置 SSL(HTTPS),通常有两种常见方式:


一、Node.js 直接使用 SSL(推荐用于简单服务)

1. 准备证书

你需要:

  • cert.pem(或 fullchain.pem
  • key.pem

如果是 Let’s Encrypt:

/etc/letsencrypt/live/yourdomain.com/fullchain.pem
/etc/letsencrypt/live/yourdomain.com/privkey.pem

2. Node.js HTTPS 示例

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 权限


二、使用 Nginx 反向代理(生产环境推荐 ✅)

1. 安装 Nginx

yum install nginx -y
systemctl enable nginx
systemctl start nginx

2. 配置 Nginx SSL

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;
}

3. Node.js 只跑 HTTP

app.listen(3000, () => {
  console.log('Node.js running on 3000');
});

三、使用 Let’s Encrypt 自动签发(CentOS)

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 必备

如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • Node.js 版本
  • 是否用 Express / Koa / Nest

我可以给你 完整可复制配置

0