在 CentOS 上配置 Node.js 应用的 SSL 证书,可以按照以下步骤进行:
首先,你需要获取一个 SSL 证书。你可以从 Let’s Encrypt 免费获取证书,或者从其他证书颁发机构购买。
你可以使用 Certbot 来获取和自动续期 Let’s Encrypt 证书。
sudo yum install epel-release
sudo yum install certbot python2-certbot-nginx
然后运行 Certbot 来获取证书:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成证书的获取和配置。
假设你已经有一个 Node.js 应用,并且使用的是 Express 框架。你需要修改你的应用代码来使用 HTTPS。
确保你已经安装了 https
和 fs
模块,这些模块是 Node.js 内置的,不需要额外安装。
在你的 Node.js 应用中,创建一个 HTTPS 服务器并配置 SSL 证书。
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
// 读取 SSL 证书文件
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8'),
cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem', 'utf8')
};
// 创建 HTTPS 服务器
https.createServer(options, app).listen(443, () => {
console.log('HTTPS Server running on port 443');
});
为了确保所有流量都通过 HTTPS,你可以设置一个 HTTP 服务器来重定向所有请求到 HTTPS。
const http = require('http');
// 创建 HTTP 服务器
http.createServer((req, res) => {
res.writeHead(301, { 'Location': `https://${req.headers.host}${req.url}` });
res.end();
}).listen(80);
确保你的 Node.js 应用已经正确配置了 HTTPS,并且可以通过浏览器访问。
打开浏览器并访问 https://yourdomain.com
,你应该能够看到你的应用,并且浏览器地址栏会显示安全锁图标。
Let’s Encrypt 证书的有效期是 90 天,因此你需要设置自动续期。
Certbot 提供了一个自动续期的脚本,你可以将其添加到 cron 任务中。
sudo crontab -e
添加以下行:
0 0,12 * * * certbot renew --post-hook "systemctl reload nginx"
这会每天检查证书是否需要续期,并在续期后重新加载 Nginx 配置。
通过以上步骤,你就可以在 CentOS 上为你的 Node.js 应用配置 SSL 证书了。