🔒 Certbot / Let's Encrypt

免費 SSL 憑證自動申請與續期工具

Certbot 是 Let's Encrypt 的官方用戶端,可自動申請 90 天免費 DV SSL/TLS 憑證並在系統 cron 中設定自動續期,支援 Nginx、Apache、Standalone 等驗證模式。

Let's Encrypt 是什麼?

Let's Encrypt 是由 Internet Security Research Group 運營的非營利憑證頒發機構(CA),提供免費的 DV(Domain Validation)SSL/TLS 憑證,每張憑證有效期 90 天,可透過 Certbot 自動申請與續期。

💡 申請前確認:① 網域已解析到此伺服器 IP,② 80 port 可從外網訪問(ACME HTTP-01 驗證需要),③ 防火牆允許 80/443 port。

安裝 Certbot

$ sudo apt install -y certbot

Nginx 申請憑證(推薦)

$ sudo apt install -y python3-certbot-nginx
$ # 申請憑證並自動修改 Nginx 設定
sudo certbot --nginx -d example.com -d www.example.com

Certbot 會自動在你的 Nginx 設定中新增 443 監聽、SSL 憑證路徑,並設定 HTTP → HTTPS 重導向。

Apache 申請憑證

$ sudo apt install -y python3-certbot-apache
sudo certbot --apache -d example.com -d www.example.com

Standalone 模式(無 Web 伺服器時)

$ # 停止佔用 80 port 的服務
sudo systemctl stop nginx

# 使用 Certbot 內建的臨時 HTTP 伺服器申請
sudo certbot certonly --standalone -d example.com

# 申請完成後恢復
sudo systemctl start nginx

憑證存放於 /etc/letsencrypt/live/example.com/

/etc/letsencrypt/live/example.com/
├── cert.pem      # 憑證本體
├── chain.pem     # 中間憑證鏈
├── fullchain.pem # cert + chain(Nginx 使用此檔)
└── privkey.pem   # 私鑰(權限 600,請勿公開)

自動續期設定

Certbot 安裝時已自動建立 systemd timer 或 cron 工作,每天嘗試續期即將到期的憑證:

$ # 查看自動續期計時器
sudo systemctl status certbot.timer
$ # 手動測試續期(--dry-run 不實際執行)
sudo certbot renew --dry-run
$ # 強制立即續期(憑證還未到期也執行)
sudo certbot renew --force-renewal

萬用字元憑證(DNS-01 驗證)

萬用字元憑證(*.example.com)需要 DNS-01 驗證,要求你能操作 DNS TXT 記錄:

$ sudo certbot certonly \
  --manual \
  --preferred-challenges dns \
  -d example.com \
  -d "*.example.com"

Certbot 會顯示要建立的 _acme-challenge.example.com TXT 記錄值,在 DNS 管理後台新增後按 Enter 繼續。

常見問題

✕ Error: Could not bind to IPv4 (port 80)
原因
Standalone 模式下,80 port 仍被其他程序佔用。
解法
先停止 Nginx/Apache:sudo systemctl stop nginx,再執行 certbot,申請後重新啟動。
✕ Too many certificates already issued for exact set of domains
原因
每個網域每週有 5 張憑證的申請上限,已達到限制。
解法
等待一週後再申請,或加入 --staging 旗標使用測試環境做除錯(不計入配額)。