在CentOS上为Node.js应用程序配置SSL证书,通常需要以下几个步骤:
获取SSL证书 首先,你需要一个SSL证书。你可以从证书颁发机构(CA)购买,或者使用Let’s Encrypt免费获取。
安装Node.js 如果你还没有安装Node.js,请按照以下命令安装:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
这里我们使用的是Node.js 14.x版本,你可以根据需要选择其他版本。
https模块和提供证书文件路径来实现。例如:const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('/path/to/your/private-key.pem', 'utf8'),
cert: fs.readFileSync('/path/to/your/certificate.pem', 'utf8')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(443);
将/path/to/your/private-key.pem和/path/to/your/certificate.pem替换为你的实际证书文件路径。
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
sudo systemctl restart your-nodejs-app.service
将your-nodejs-app.service替换为你的实际Node.js应用程序服务名称。
现在,你的Node.js应用程序应该已经成功配置了SSL证书,并可以通过HTTPS访问了。