温馨提示×

ubuntu nodejs如何开启https

小樊
46
2026-09-30 23:58:56
栏目: 编程语言

在 Ubuntu 上让 Node.js 开启 HTTPS,通常有两种常见方式:


一、Node.js 原生 HTTPS(推荐用于学习/自建服务)

1. 准备证书

你需要:

  • server.key(私钥)
  • server.crt(证书)

本地测试可用自签名证书:

sudo apt update
sudo apt install -y openssl

openssl req -nodes -new -x509 \
  -keyout server.key -out server.crt \
  -days 365

2. 编写 Node.js HTTPS 服务

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

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

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

3. 运行(端口 < 1024 需权限)

sudo node server.js

浏览器访问:

https://localhost

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

1. 安装 Nginx

sudo apt install nginx

2. 配置 HTTPS

sudo nano /etc/nginx/sites-available/default

示例:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/certs/fullchain.pem;
    ssl_certificate_key /etc/ssl/private/privkey.pem;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
    }
}

3. Node.js 只跑 HTTP

const http = require('http');
http.createServer((req, res) => {
  res.end('Hello');
}).listen(3000);

4. 重启 Nginx

sudo nginx -t
sudo systemctl restart nginx

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

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

常见问题

  • 端口占用:检查 80 / 443 是否被占用
  • 权限问题:Node 直接用 443 需 sudo
  • 浏览器不信任:自签证书需手动信任

如果你告诉我:

  • 是否生产环境
  • 是否已有域名
  • Node 版本

我可以给你更精确的配置。

0 踩