CentOS Node.js如何配置SSL证书

1073
2025/2/14 21:31:57
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上配置Node.js应用程序的SSL证书,可以按照以下步骤进行:

1. 获取SSL证书

首先,你需要一个SSL证书。你可以从以下几个途径获取:

  • Let’s Encrypt:提供免费的SSL证书。
  • 购买商业证书:从证书颁发机构(CA)购买。

使用Let’s Encrypt获取证书

你可以使用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

按照提示完成证书的获取和配置。

2. 配置Node.js应用程序

假设你已经有一个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);

3. 重定向HTTP到HTTPS

为了确保所有流量都通过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);

4. 自动续期证书

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传输。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Java日志在CentOS上的存储策略有哪些