在 CentOS 上為 Node.js 應用添加 SSL 證書,可以按照以下步驟進行操作:
首先,你需要獲取一個 SSL 證書。你可以從 Let’s Encrypt 免費獲取證書,或者購買一個商業證書。
安裝 Certbot:
sudo yum install epel-release
sudo yum install certbot python2-certbot-nginx
運行 Certbot 獲取證書:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成證書的獲取和配置。
如果你使用 Nginx 作為反向代理服務器,可以在 Nginx 配置文件中設置 SSL。
編輯 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/default.conf
):
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
proxy_pass http://localhost:3000; # 你的 Node.js 應用監聽的端口
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;
}
}
重新加載 Nginx 配置:
sudo systemctl reload nginx
確保你的 Node.js 應用監聽在正確的端口上(例如 3000),并且能夠處理 HTTPS 請求。
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(3000, () => {
console.log('Server is running on https://yourdomain.com:3000');
});
打開瀏覽器,訪問 https://yourdomain.com
,你應該能夠看到你的 Node.js 應用,并且瀏覽器地址欄會顯示安全鎖圖標,表示 SSL 配置成功。
Let’s Encrypt 的證書有效期為 90 天,因此需要設置自動續期。
編輯 Certbot 的續期腳本:
sudo crontab -e
添加以下行以每天檢查并續期證書:
0 0 * * * certbot renew --post-hook "systemctl reload nginx"
通過以上步驟,你就可以在 CentOS 上為 Node.js 應用成功添加 SSL 證書了。