在 Linux 下为 Node.js 应用配置 SSL 证书,可以按照以下步骤进行:
首先,你需要获取一个 SSL 证书。你可以从以下途径获取:
你可以使用 Certbot 工具来获取 Let’s Encrypt 证书。以下是安装和使用 Certbot 的步骤:
# 安装 Certbot
sudo apt update
sudo apt install certbot
# 获取证书
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
假设你已经有一个 Node.js 应用,并且使用的是 Express 框架。以下是如何配置 SSL 证书的示例:
确保你已经安装了 express 和 https 模块:
npm install express https fs
创建一个文件(例如 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');
});
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"
确保你的 Node.js 应用已经正确配置并运行在 HTTPS 上。你可以通过访问 https://yourdomain.com 来测试。
通过以上步骤,你应该能够在 Linux 下成功为 Node.js 应用配置 SSL 证书。