溫馨提示×

如何在Ubuntu上配置Node.js的SSL證書

小樊
45
2025-09-23 08:44:39
欄目: 云計算

在Ubuntu上配置Node.js應用程序的SSL證書,通常涉及以下幾個步驟:

1. 獲取SSL證書

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

  • Let’s Encrypt:提供免費的SSL證書。
  • 購買商業證書:從證書頒發機構(CA)購買。

使用Let’s Encrypt獲取證書

  1. 安裝Certbot:

    sudo apt update
    sudo apt install certbot
    
  2. 運行Certbot獲取證書:

    sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
    

    按照提示完成證書的獲取和安裝。

2. 配置Node.js應用程序

假設你已經有一個Node.js應用程序,并且使用Express框架。

  1. 安裝必要的Node.js模塊:

    npm install express https fs
    
  2. 創建一個SSL配置文件(例如ssl-config.js):

    const fs = require('fs');
    const https = require('https');
    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')
    };
    
    // 定義路由
    app.get('/', (req, res) => {
      res.send('Hello, SSL!');
    });
    
    // 啟動HTTPS服務器
    https.createServer(options, app).listen(443, () => {
      console.log('Server is running on https://yourdomain.com');
    });
    

3. 自動續期證書

Let’s Encrypt證書每90天需要續期一次。你可以使用Certbot的自動續期功能。

  1. 創建一個續期腳本:

    sudo nano /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  2. 添加以下內容到續期腳本:

    #!/bin/bash
    systemctl reload nginx  # 或者你使用的其他Web服務器
    
  3. 賦予腳本執行權限:

    sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  4. 測試續期腳本:

    sudo /etc/letsencrypt/renewal-hooks/deploy/renewal.sh
    
  5. 設置定時任務自動續期:

    sudo crontab -e
    

    添加以下行:

    0 0,12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot renew --deploy-hook "/etc/letsencrypt/renewal-hooks/deploy/renewal.sh"
    

4. 重啟Node.js應用程序

每次續期證書后,你需要重啟Node.js應用程序以應用新的證書。

sudo systemctl restart your-node-app

通過以上步驟,你可以在Ubuntu上成功配置Node.js應用程序的SSL證書,并確保證書自動續期。

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