🌐 Caddy

自動 HTTPS 的現代輕量 Web 伺服器

Caddy 以 Go 撰寫,預設自動申請並續期 Let's Encrypt 憑證,Caddyfile 設定語法簡潔直觀,適合快速部署個人專案與小型 API。

安裝

$ sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update && sudo apt install -y caddy
sudo systemctl enable --now caddy

Caddyfile 語法

Caddy 的設定檔(/etc/caddy/Caddyfile)語法極為簡潔:

# 格式:<地址> { <指令> }

example.com {
    root * /var/www/html
    file_server
}

# 多個網域共用設定
example.com, www.example.com {
    ...
}
💡 Caddy 2 預設會自動向 Let's Encrypt 申請 HTTPS 憑證。只要設定了有效網域,無需任何額外步驟。

靜態網站設定

example.com {
    root * /var/www/example.com
    file_server

    # 壓縮
    encode gzip zstd

    # 自訂 404 頁面
    handle_errors {
        rewrite * /404.html
        file_server
    }
}

反向代理(Node.js / Python)

api.example.com {
    reverse_proxy localhost:3000

    # 健康檢查
    reverse_proxy localhost:3000 {
        health_uri /health
        health_interval 30s
    }
}

# 多個後端負載均衡
app.example.com {
    reverse_proxy localhost:3001 localhost:3002 {
        lb_policy round_robin
    }
}

自動 HTTPS 說明

Caddy 使用 ACME 協定自動管理憑證,條件:

# 本機開發:停用 HTTPS(使用 http://)
http://localhost {
    root * /var/www/dev
    file_server
    browse
}

常用操作

操作指令
驗證 Caddyfile 語法caddy validate --config /etc/caddy/Caddyfile
重新載入設定sudo systemctl reload caddy
查看狀態sudo systemctl status caddy
格式化 Caddyfilesudo caddy fmt --overwrite /etc/caddy/Caddyfile
查看憑證資訊sudo caddy list-modules
即時查看日誌sudo journalctl -u caddy -f