在Linux上為Node.js應用程序配置SSL,您需要首先獲取一個SSL證書。您可以選擇購買一個證書,或者使用免費的Let’s Encrypt證書。以下是使用Let’s Encrypt證書配置SSL的步驟:
對于基于Debian的系統(如Ubuntu):
sudo apt-get update
sudo apt-get install certbot python3-certbot-nginx
對于基于RHEL的系統(如CentOS、Fedora):
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx
yourdomain.com替換為您的域名:sudo certbot --nginx -d yourdomain.com
Certbot將自動配置Nginx以使用SSL,并將證書文件存儲在/etc/letsencrypt/live/yourdomain.com/目錄中。
const https = require('https');
const fs = require('fs');
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.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello, SSL!');
}).listen(443);
在這個示例中,我們從Let’s Encrypt證書目錄中讀取私鑰和證書文件,并將它們作為選項傳遞給HTTPS服務器。
重啟Node.js應用程序: 保存更改并重新啟動Node.js應用程序以應用新的SSL配置。
更新證書: Certbot會自動為您更新證書,但在證書到期前30天,它會發送提醒。要手動更新證書,請運行以下命令:
sudo certbot renew
現在,您的Node.js應用程序已成功配置了SSL,并可以通過HTTPS訪問。