在Ubuntu上配置Node.js應用程序的SSL證書,通常涉及以下幾個步驟:
首先,你需要一個SSL證書。你可以從以下幾種方式獲?。?/p>
安裝Certbot:
sudo apt update
sudo apt install certbot
運行Certbot獲取證書:
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
按照提示完成證書的獲取和安裝。
假設你已經有一個Node.js應用程序,并且使用Express框架。
安裝必要的Node.js模塊:
npm install express https fs
創建一個SSL配置文件(例如ssl-config.js
):
const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();
// 讀取SSL證書文件
const options = {
key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem', 'utf8'),
cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem', 'utf8')
};
// 定義路由
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的自動續期功能。
創建一個續期腳本:
sudo nano /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
添加以下內容到續期腳本:
#!/bin/bash
systemctl reload nginx # 或者你使用的其他Web服務器
賦予腳本執行權限:
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
測試續期腳本:
sudo /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
設置定時任務自動續期:
sudo crontab -e
添加以下行:
0 0,12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot renew --deploy-hook "/etc/letsencrypt/renewal-hooks/deploy/renewal.sh"
每次續期證書后,你需要重啟Node.js應用程序以應用新的證書。
sudo systemctl restart your-node-app
通過以上步驟,你可以在Ubuntu上成功配置Node.js應用程序的SSL證書,并確保證書自動續期。