Skip to content

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

靜態檔案

file_server 把目錄裡的 HTML、CSS、圖片等直接送給瀏覽器。Caddy 支援 Range、ETag,也能邊傳邊壓縮,足夠當正式靜態站,不只是本機隨便開一個目錄。

官方:Static files 快速入門file_server

基本用法

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

root 指定網站根目錄。請求 /about.html 時,Caddy 讀 /var/www/html/about.html。目錄請求會找 index.html

本機快速試:

caddy file-server --root ./public --browse

--browse 在沒有 index 時顯示目錄列表,適合內網檔案櫃,不適合把整個磁碟暴露到公網。

壓縮

example.com {
    root * /srv
    encode gzip zstd
    file_server
}

encode 會依客戶端 Accept-Encoding 壓縮回應。Caddy 也支援預先壓好的 .gz.zst,用 file_serverprecompressed 可少耗 CPU。

與反向代理並存

靜態前端 + API 後端是常見組合:

example.com {
    root * /srv/site

    handle /api/* {
        reverse_proxy 127.0.0.1:8080
    }

    handle {
        file_server
    }
}

單頁應用(SPA)若所有路徑都要回到 index.html,在 file_server 前加 try_files {path} /index.html

權限

以套件安裝時,行程使用者是 caddy。網站目錄必須對該使用者可讀;上傳或寫入還要可寫。Docker 則把主機目錄掛到容器的 /srv,並在 Caddyfile 寫 root * /srv

更多標頭、快取與轉址見 常用指令