溫馨提示×

Ubuntu Node.js如何配置SSL證書

小樊
43
2025-07-01 17:19:38
欄目: 云計算

在Ubuntu上為Node.js應用程序配置SSL證書,可以按照以下步驟進行:

1. 獲取SSL證書

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

  • Let’s Encrypt:免費且自動化的證書頒發機構。
  • 購買證書:從商業證書頒發機構購買。

使用Let’s Encrypt獲取證書

你可以使用certbot工具來獲取和續訂Let’s Encrypt證書。

  1. 安裝certbot

    sudo apt update
    sudo apt install certbot python3-certbot-nginx
    
  2. 獲取證書:

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

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

2. 配置Nginx反向代理

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

  1. 編輯Nginx配置文件:

    sudo nano /etc/nginx/sites-available/yourdomain.com
    
  2. 添加或修改以下配置:

    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com;
        return 301 https://$host$request_uri;
    }
    
    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;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
    
        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;
        }
    }
    
  3. 啟用配置:

    sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl restart nginx
    

3. 配置Node.js應用

如果你的Node.js應用直接監聽443端口,你需要修改應用的配置。

  1. 修改Node.js應用的監聽端口(例如,改為3000):
    const express = require('express');
    const app = express();
    const https = require('https');
    const fs = require('fs');
    
    const options = {
        key: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/privkey.pem'),
        cert: fs.readFileSync('/etc/letsencrypt/live/yourdomain.com/fullchain.pem')
    };
    
    app.get('/', (req, res) => {
        res.send('Hello World!');
    });
    
    https.createServer(options, app).listen(3000, () => {
        console.log('Server running on https://yourdomain.com:3000');
    });
    

4. 自動續訂證書

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

  1. 編輯/etc/letsencrypt/renewal-hooks/deploy/renewal.sh文件,添加以下內容:

    systemctl reload nginx
    
  2. 設置定時任務:

    sudo crontab -e
    

    添加以下行:

    0 0,12 * * * root certbot renew --post-hook "systemctl reload nginx"
    

通過以上步驟,你可以在Ubuntu上為Node.js應用程序配置SSL證書,并確保證書能夠自動續訂。

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