Skip to Content
👋 嘿,快來看看全新 RWA 交易協議 Buxx.finance
文章NEW後端在 3 分鐘內生成免費SSL憑證

在 3 分鐘內生成免費SSL憑證

Nginx + Express + Let’s Encrypt

你是否曾經被 SSL 憑證搞得頭昏腦脹?還在猶豫要不要掏錢買個 SSL?別擔心,這篇文章將教你如何在 3 分鐘內,透過 Node.js + Express + LetsEncrypt,讓你的網站從 HTTP 搖身一變成為 HTTPS,而且完全 免費! 🎉

🛠️ 你需要準備的東西

  • 一台伺服器(VPS、雲端主機或家裡的樹莓派)
  • 已指向伺服器的網域名稱(免費的 duckdns.org 也行)
  • Node.js(至少 v20+)
  • Nginx(選擇性,但推薦使用)

🔥 開始

1️⃣ 安裝必要的工具

我們將使用 certbot 來申請 SSL 憑證,首先要安裝它。

Ubuntu / Debian:

sudo apt update && sudo apt install certbot

2️⃣ 申請 SSL 憑證

使用 certbot 申請 SSL 憑證,假設你的網域是 example.com:

sudo certbot certonly --standalone -d example.com

這時候 certbot 會要求你輸入 Email,並同意 Let’s Encrypt 的條款,成功後,你的憑證會被存放在:

/etc/letsencrypt/live/example.com/

裡面包含:

  • fullchain.pem(完整憑證鏈)
  • privkey.pem(私鑰,如果洩漏請立即重新生成憑證)

3️⃣ 設定 Nginx 反向代理來使用 HTTPS

我們使用 Nginx 來處理 HTTPS 流量,並將請求轉發給 Express 應用。

首先,安裝 Nginx(如果尚未安裝):

sudo apt install nginx -y

然後編輯 Nginx 設定檔:

sudo vim /etc/nginx/sites-available/example.com

加入以下內容:

server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name example.com www.example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.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; } }

啟用 Nginx 設定:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

測試並重新啟動 Nginx:

sudo nginx -t sudo systemctl restart nginx

4️⃣ 啟動 Express 應用(也可以是 Golang、Python 等)

在你的 Express 應用中,確保它運行在 localhost:3000,內容如下:

const express = require("express"); const app = express(); app.get("/", (req, res) => { res.send("Hello, HTTPS via Nginx Reverse Proxy! 🔒"); }); app.listen(3000, () => { console.log("🚀 Express 伺服器運行於 http://localhost:3000"); });

📌 讓憑證自動更新

Let’s Encrypt 憑證有效期只有 90 天,但我們可以用 cron 來自動續約。

執行以下指令,確認 certbot 自動更新:

sudo certbot renew --dry-run

若測試成功,設定 crontab 讓它每天檢查並更新:

crontab -e

加入以下內容,每天凌晨自動檢查憑證並更新:

0 0 * * * certbot renew --quiet --post-hook "systemctl restart nginx"

🎉 完成

恭喜你!現在你的 Express 伺服器已經擁有 免費的 HTTPS,而且它會自動續約,不用擔心憑證過期! 🚀

如果你還想進一步優化,可以考慮設定 防火牆負載平衡 來提升安全性和效能。

💡 現在就試試吧,讓你的網站更安全! 🔐

最後更新於: