温馨提示×

CentOS Node.js如何配置SSL证书

小樊
85
2025-02-14 19:50:54
栏目: 云计算
亿速云SSL证书,防劫持篡改、防监听窃取、提升搜索排名 点击了解>>

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

亿速云提供多种品牌、不同类型SSL证书签发服务,包含:域名型、企业型、企业型专业版、增强型以及增强型专业版,单域名SSL证书300元/年起。点击查看>>

推荐阅读:如何在 CentOS 上为 Node.js 应用添加 SSL 证书

0