在CentOS上配置Node.js应用程序的SSL证书,可以按照以下步骤进行:
首先,你需要一个SSL证书。你可以从以下几个途径获取:
你可以使用Certbot
工具来获取Let’s Encrypt证书。以下是安装和配置Certbot的步骤:
# 安装EPEL仓库
sudo yum install epel-release
# 安装Certbot
sudo yum install certbot python2-certbot-apache
# 获取证书
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
按照提示完成证书的获取和配置。
假设你已经有一个Node.js应用程序运行在某个端口(例如3000),你可以使用http
模块或express
框架来配置SSL。
http
模块const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(443);
express
框架如果你使用的是express
,可以这样配置:
const express = require('express');
const https = require('https');
const fs = require('fs');
const app = express();
app.get('/', (req, res) => {
res.send('hello world!');
});
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};
https.createServer(options, app).listen(443);
为了确保所有流量都通过HTTPS,你可以配置一个HTTP服务器来重定向所有请求到HTTPS。
const http = require('http');
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('hello world!');
});
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};
https.createServer(options, app).listen(443);
http.createServer((req, res) => {
res.writeHead(301, { "Location": `https://${req.headers.host}${req.url}` });
res.end();
}).listen(80);
Let’s Encrypt证书每90天会过期一次,你需要设置自动续期。
# 安装Certbot的自动续期工具
sudo yum install certbot-cron
# 启动自动续期服务
sudo systemctl start certbot-cron.service
sudo systemctl enable certbot-cron.service
这样,Certbot会自动检查并续期你的证书。
通过以上步骤,你可以在CentOS上为你的Node.js应用程序配置SSL证书,并确保所有流量都通过HTTPS传输。
亿速云提供多种品牌、不同类型SSL证书签发服务,包含:域名型、企业型、企业型专业版、增强型以及增强型专业版,单域名SSL证书300元/年起。点击查看>>
推荐阅读:如何在 CentOS 上为 Node.js 应用添加 SSL 证书