linux

Linux 下 Node.js 如何配置 SSL 证书

小樊
43
2025-09-29 11:16:13
栏目: 云计算

在 Linux 下为 Node.js 应用配置 SSL 证书,可以按照以下步骤进行:

1. 获取 SSL 证书

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

使用 Let’s Encrypt 获取证书

你可以使用 Certbot 工具来获取 Let’s Encrypt 证书。以下是安装和使用 Certbot 的步骤:

# 安装 Certbot
sudo apt update
sudo apt install certbot

# 获取证书
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com

2. 配置 Node.js 应用

假设你已经有一个 Node.js 应用,并且使用的是 Express 框架。以下是如何配置 SSL 证书的示例:

安装必要的模块

确保你已经安装了 expresshttps 模块:

npm install express https fs

配置 HTTPS 服务器

创建一个文件(例如 server.js),并添加以下代码:

const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

// 读取 SSL 证书文件
const options = {
  key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
  cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
};

// 定义路由
app.get('/', (req, res) => {
  res.send('Hello, SSL!');
});

// 启动 HTTPS 服务器
https.createServer(options, app).listen(443, () => {
  console.log('Server is running on https://yourdomain.com');
});

3. 自动续期证书

Let’s Encrypt 证书的有效期为 90 天,因此你需要设置自动续期。Certbot 提供了自动续期的功能。

设置自动续期

编辑 Certbot 的续期配置文件:

sudo nano /etc/letsencrypt/renewal-hooks/deploy/post.sh

添加以下内容:

#!/bin/bash

# 重启 Node.js 应用以应用新的证书
systemctl restart your-nodejs-service

确保脚本有执行权限:

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/post.sh

然后,编辑 Certbot 的续期配置文件:

sudo nano /etc/letsencrypt/renewal-hooks/deploy/install-post.sh

添加以下内容:

#!/bin/bash

# 启动 Node.js 应用
systemctl start your-nodejs-service

确保脚本有执行权限:

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/install-post.sh

最后,设置自动续期任务:

sudo crontab -e

添加以下行:

0 0,12 * * * certbot renew --post-hook "systemctl restart your-nodejs-service"

4. 测试配置

确保你的 Node.js 应用已经正确配置并运行在 HTTPS 上。你可以通过访问 https://yourdomain.com 来测试。

通过以上步骤,你应该能够在 Linux 下成功为 Node.js 应用配置 SSL 证书。

0
看了该问题的人还看了