溫馨提示×

如何在 CentOS 上為 Node.js 應用添加 SSL 證書

小樊
118
2025-02-12 06:53:18
欄目: 云計算

在 CentOS 上為 Node.js 應用添加 SSL 證書,可以按照以下步驟進行操作:

1. 獲取 SSL 證書

首先,你需要獲取一個 SSL 證書。你可以從 Let’s Encrypt 免費獲取證書,或者購買一個商業證書。

使用 Let’s Encrypt 獲取證書

  1. 安裝 Certbot:

    sudo yum install epel-release
    sudo yum install certbot python2-certbot-nginx
    
  2. 運行 Certbot 獲取證書:

    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
    

    按照提示完成證書的獲取和配置。

2. 配置 Nginx 反向代理

如果你使用 Nginx 作為反向代理服務器,可以在 Nginx 配置文件中設置 SSL。

  1. 編輯 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;
        }
    }
    
  2. 重新加載 Nginx 配置:

    sudo systemctl reload nginx
    

3. 配置 Node.js 應用

確保你的 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');
});

4. 測試 SSL 配置

打開瀏覽器,訪問 https://yourdomain.com,你應該能夠看到你的 Node.js 應用,并且瀏覽器地址欄會顯示安全鎖圖標,表示 SSL 配置成功。

5. 自動續期證書

Let’s Encrypt 的證書有效期為 90 天,因此需要設置自動續期。

  1. 編輯 Certbot 的續期腳本:

    sudo crontab -e
    
  2. 添加以下行以每天檢查并續期證書:

    0 0 * * * certbot renew --post-hook "systemctl reload nginx"
    

通過以上步驟,你就可以在 CentOS 上為 Node.js 應用成功添加 SSL 證書了。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女