在CentOS環境下配置Node.js應用程序的SSL,你需要遵循以下步驟:
如果你還沒有安裝Node.js,請先安裝它。你可以從Node.js官方網站下載并安裝適用于CentOS的安裝包?;蛘?,你可以使用NodeSource二進制分發庫來安裝特定版本的Node.js。要使用NodeSource,請按照以下命令操作:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
這將安裝Node.js 14.x版本。你可以根據需要更改版本號。
創建一個新的Node.js應用程序,或者使用現有的應用程序。確保你的應用程序包含一個HTTP服務器,如下所示:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
要啟用SSL,你需要一個SSL證書。你可以從Let’s Encrypt免費獲取一個證書。安裝Certbot客戶端并獲取證書:
sudo yum install epel-release
sudo yum install certbot python2-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
按照提示操作,完成證書的獲取和安裝。
修改你的Node.js應用程序,以便它使用SSL證書。你需要使用https
模塊而不是http
模塊,并提供證書文件的路徑。這是一個示例:
const https = require('https');
const fs = require('fs');
const privateKey = fs.readFileSync('path/to/your/private-key.pem', 'utf8');
const certificate = fs.readFileSync('path/to/your/certificate.pem', 'utf8');
const ca = fs.readFileSync('path/to/your/ca.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate, ca: ca };
const server = https.createServer(credentials, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running at https://localhost:${PORT}/`);
});
將path/to/your/private-key.pem
、path/to/your/certificate.pem
和path/to/your/ca.pem
替換為你的證書文件的實際路徑。
保存更改并重新啟動你的Node.js應用程序:
node your-app.js
現在,你的Node.js應用程序應該已經通過HTTPS運行,并使用SSL證書。訪問https://yourdomain.com:3000
(或你選擇的端口)以查看安全連接。