在 Linux 上配置 Node.js 应用以支持 HTTPS 需要以下几个步骤:
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。
// 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.pem 和 path/to/your/fullchain.pem 替换为你的 SSL 证书文件路径。
node app.js
现在,你的 Node.js 应用已经通过 HTTPS 运行在端口 443 上。
注意:在生产环境中,建议使用进程管理器(如 PM2)来运行 Node.js 应用,以确保应用在遇到错误时自动重启。要使用 PM2,请先安装它:
sudo npm install -g pm2
然后使用以下命令启动你的应用:
pm2 start app.js
这样,你的 Node.js 应用将更加稳定且易于管理。