Skip to content

建立 2026-09-15 更新 2026-09-15

常用指令

Caddyfile 的指令(directive)負責「這個站要做什麼」。下面是除了 reverse_proxyfile_server 之外,最常一起出現的幾個。完整列表與執行順序見 Directives

handle 與 handle_path

handle 區塊互斥:請求只會進第一個匹配的 handle。適合依路徑拆後端。

example.com {
    handle /blog/* {
        reverse_proxy 127.0.0.1:4000
    }

    handle {
        file_server
    }
}

handle_path /blog/* 會先去掉 /blog 前綴再處理。後端路由若從 / 起算就用它;若後端仍要看到 /blog,用 handle

redir 與 rewrite

  • redir:告訴瀏覽器改去別的網址(對外可見)。
  • rewrite:只改伺服器內部看到的路徑(瀏覽器網址列不變)。
www.example.com {
    redir https://example.com{uri} permanent
}

example.com {
    rewrite /old /new
    file_server
}

{uri} 是佔位符(placeholder),代表原始路徑與查詢字串。常用佔位符還有 {host}{path}{remote_host}

加減回應標頭:

example.com {
    header {
        X-Content-Type-Options nosniff
        -Server
    }
    file_server
}

-Server 表示刪除該標頭。HSTS、CSP 等安全標頭也在這裡加,但內容要符合你實際的前端與第三方腳本,亂加會把網站弄壞。

encode

encode gzip zstd

通常放在站台區塊裡,與 file_serverreverse_proxy 一起用。後端若已經壓縮,Caddy 會避免重複壓。

basic_auth

保護內網工具或預覽站:

example.com {
    basic_auth {
        alice $2a$14$...
    }
    reverse_proxy 127.0.0.1:8080
}

雜湊用 caddy hash-password 產生。Caddy 2.8 起指令名是 basic_auth(舊名 basicauth 仍能用一段時間)。這只是瀏覽器基本認證,不是完整的使用者系統。

log

example.com {
    log {
        output file /var/log/caddy/access.log
    }
    reverse_proxy 127.0.0.1:3000
}

沒寫時,存取日誌多半進 journald 或容器 stdout。正式環境建議明確指定路徑與輪替方式。

php_fastcgi

傳統 PHP(php-fpm)用 php_fastcgi;若使用 FrankenPHP,則是另一套 php_server 流程。WordPress 最小例子:

example.com {
    root * /var/www/wordpress
    encode
    php_fastcgi unix//run/php/php-fpm.sock
    file_server
}

官方站自己的 Caddyfile 也是靜態檔 + 少量 rewritereverse_proxy,可當可讀性參考:caddyserver.com 實際設定