在 Linux 上為 Node.js 配置 SSL 證書,可以按照以下步驟進行操作:
首先,你需要一個 SSL 證書。你可以從以下幾種方式獲?。?/p>
你可以使用 certbot
工具來獲取 Let’s Encrypt 證書。以下是安裝和使用 certbot
的步驟:
# 安裝 certbot 和 certbot-apache(如果你使用的是 Apache)
sudo apt update
sudo apt install certbot python3-certbot-apache
# 運行 certbot 獲取證書
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
假設你已經有一個 Node.js 應用,并且你希望它使用 SSL 證書。你可以使用 https
模塊來創建一個 HTTPS 服務器。
const https = require('https');
const fs = require('fs');
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')
};
// 創建 HTTPS 服務器
https.createServer(options, app).listen(443, () => {
console.log('HTTPS Server running on port 443');
});
Let’s Encrypt 證書通常有效期為 90 天,因此你需要設置自動續期。certbot
提供了自動續期的功能。
# 設置自動續期
sudo crontab -e
# 添加以下行以每天檢查一次續期
0 0 * * * /usr/bin/certbot renew --post-hook "systemctl reload nginx"
如果你使用的是 Nginx 或 Apache 作為反向代理,你可以配置它們來轉發請求到你的 Node.js 應用,并使用 SSL 證書。
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
<VirtualHost *:443>
ServerName yourdomain.com www.yourdomain.com
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
</VirtualHost>
最后,重啟你的 Node.js 應用和反向代理服務以應用更改。
# 重啟 Node.js 應用
sudo systemctl restart your-node-app
# 重啟 Nginx 或 Apache
sudo systemctl restart nginx
# 或者
sudo systemctl restart apache2
通過以上步驟,你就可以在 Linux 上為 Node.js 配置 SSL 證書,并確保你的應用通過 HTTPS 提供服務。