在Debian系统上为Node.js应用配置SSL证书,可以按照以下步骤进行:
首先,你需要获取一个SSL证书。你可以从Let’s Encrypt免费获取,或者从其他证书颁发机构购买。
安装Certbot:
sudo apt update
sudo apt install certbot
运行Certbot以获取证书:
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
按照提示完成证书的申请和验证过程。
假设你的Node.js应用运行在http://localhost:3000
,你可以使用express
框架来配置SSL。
npm install express https fs
在你的Node.js应用目录下创建一个ssl-config.js
文件,内容如下:
const fs = require('fs');
const https = require('https');
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};
const app = require('./app'); // 你的Express应用
https.createServer(options, app).listen(443, () => {
console.log('Server is running on https://yourdomain.com');
});
确保你的防火墙允许HTTPS流量(端口443):
sudo ufw allow 443/tcp
重启你的Node.js应用以应用新的SSL配置:
pm2 restart your-app-name
或者如果你没有使用pm2
,可以直接运行你的Node.js应用:
node ssl-config.js
Let’s Encrypt证书每90天会过期一次,你需要设置自动续期。
编辑Certbot的续期脚本:
sudo nano /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
添加以下内容以重启Node.js应用:
#!/bin/sh
systemctl restart your-app-name
赋予脚本执行权限:
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
设置定时任务以每天检查证书续期:
sudo crontab -e
添加以下行:
0 0 * * * /usr/bin/certbot renew --deploy-hook "/etc/letsencrypt/renewal-hooks/deploy/renewal.sh"
通过以上步骤,你就可以在Debian系统上为Node.js应用成功配置SSL证书了。