linux

Linux Node.js 如何配置 HTTPS

小樊
37
2025-10-18 12:18:01
栏目: 编程语言

在 Linux 上配置 Node.js 应用以支持 HTTPS 需要以下几个步骤:

  1. 获取 SSL 证书 要启用 HTTPS,首先需要获得 SSL 证书。你可以从证书颁发机构(CA)购买证书,或者使用 Let’s Encrypt 提供的免费证书。以下是使用 Certbot 获取 Let’s Encrypt 证书的示例:
sudo apt-get update
sudo apt-get install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

按照提示操作,Certbot 会自动配置 Nginx 以支持 HTTPS。

  1. 创建 Node.js 应用 创建一个简单的 Node.js 应用,例如:
// app.js
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('path/to/your/privkey.pem'),
  cert: fs.readFileSync('path/to/your/fullchain.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello, HTTPS!\n');
}).listen(443);

path/to/your/privkey.pempath/to/your/fullchain.pem 替换为你的 SSL 证书文件路径。

  1. 运行 Node.js 应用 在终端中运行以下命令启动 Node.js 应用:
node app.js

现在,你的 Node.js 应用已经通过 HTTPS 运行在端口 443 上。

注意:在生产环境中,建议使用进程管理器(如 PM2)来运行 Node.js 应用,以确保应用在遇到错误时自动重启。要使用 PM2,请先安装它:

sudo npm install -g pm2

然后使用以下命令启动你的应用:

pm2 start app.js

这样,你的 Node.js 应用将更加稳定且易于管理。

0
看了该问题的人还看了