溫馨提示×

如何在 Linux 上為 Node.js 配置 SSL 證書

小樊
39
2025-04-09 13:57:33
欄目: 云計算

在 Linux 上為 Node.js 配置 SSL 證書,可以按照以下步驟進行操作:

1. 獲取 SSL 證書

首先,你需要一個 SSL 證書。你可以從以下幾種方式獲?。?/p>

  • Let’s Encrypt:提供免費的 SSL 證書。
  • 購買證書:從證書頒發機構(CA)購買。
  • 自簽名證書:適用于測試環境。

使用 Let’s Encrypt 獲取證書

你可以使用 certbot 工具來獲取 Let’s Encrypt 證書。以下是安裝和使用 certbot 的步驟:

# 安裝 certbot 和 certbot-apache(如果你使用的是 Apache)
sudo apt update
sudo apt install certbot python3-certbot-apache

# 運行 certbot 獲取證書
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

2. 配置 Node.js 應用以使用 SSL 證書

假設你已經有一個 Node.js 應用,并且你希望它使用 SSL 證書。你可以使用 https 模塊來創建一個 HTTPS 服務器。

示例代碼

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

// 讀取 SSL 證書和私鑰文件
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 服務器
https.createServer(options, app).listen(443, () => {
  console.log('HTTPS Server running on port 443');
});

3. 自動續期 Let’s Encrypt 證書

Let’s Encrypt 證書通常有效期為 90 天,因此你需要設置自動續期。certbot 提供了自動續期的功能。

# 設置自動續期
sudo crontab -e

# 添加以下行以每天檢查一次續期
0 0 * * * /usr/bin/certbot renew --post-hook "systemctl reload nginx"

4. 配置反向代理(可選)

如果你使用的是 Nginx 或 Apache 作為反向代理,你可以配置它們來轉發請求到你的 Node.js 應用,并使用 SSL 證書。

Nginx 配置示例

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;

    location / {
        proxy_pass http://localhost:3000;
        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;
    }
}

Apache 配置示例

<VirtualHost *:443>
    ServerName yourdomain.com www.yourdomain.com

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem

    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/
</VirtualHost>

5. 重啟服務

最后,重啟你的 Node.js 應用和反向代理服務以應用更改。

# 重啟 Node.js 應用
sudo systemctl restart your-node-app

# 重啟 Nginx 或 Apache
sudo systemctl restart nginx
# 或者
sudo systemctl restart apache2

通過以上步驟,你就可以在 Linux 上為 Node.js 配置 SSL 證書,并確保你的應用通過 HTTPS 提供服務。

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