在Ubuntu上為Node.js應用程序配置SSL證書,可以按照以下步驟進行:
首先,你需要一個SSL證書。你可以從以下幾種方式獲?。?/p>
你可以使用certbot
工具來獲取和續訂Let’s Encrypt證書。
安裝certbot
:
sudo apt update
sudo apt install certbot python3-certbot-nginx
獲取證書:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示完成證書的獲取和配置。
如果你使用Nginx作為反向代理,可以在Nginx配置文件中設置SSL。
編輯Nginx配置文件:
sudo nano /etc/nginx/sites-available/yourdomain.com
添加或修改以下配置:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
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;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
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;
}
}
啟用配置:
sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
如果你的Node.js應用直接監聽443端口,你需要修改應用的配置。
const express = require('express');
const app = express();
const https = require('https');
const fs = require('fs');
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 World!');
});
https.createServer(options, app).listen(3000, () => {
console.log('Server running on https://yourdomain.com:3000');
});
Let’s Encrypt證書每90天需要續訂一次。你可以使用certbot
的自動續訂功能。
編輯/etc/letsencrypt/renewal-hooks/deploy/renewal.sh
文件,添加以下內容:
systemctl reload nginx
設置定時任務:
sudo crontab -e
添加以下行:
0 0,12 * * * root certbot renew --post-hook "systemctl reload nginx"
通過以上步驟,你可以在Ubuntu上為Node.js應用程序配置SSL證書,并確保證書能夠自動續訂。