Cloudflare Worker

最後更新

本頁說明 worker/index.js 如何在 Cloudflare 邊緣快取圖片,以及部署步驟。

行為

項目 行為
接受的路徑 結尾為 .jpg、.jpeg、.png、.webp、.svg(不分大小寫);其他一律回 400 文字 400
轉發 保留原路徑與所有 query 參數,轉發至來源 [URL]
快取鍵 完整來源 URL 的 Request,附 X-Custom-Cache-Key: {query string 或 no-query}
快取儲存 caches.default,回應改寫 Cache-Control: public, max-age=604800 後以 event.waitUntil(cache.put(...)) 寫入
回應標頭 CF-Cache-Status: HIT/MISS、X-Query-String: {query string 或 none}

部署

  1. 將 worker/index.js 中的 [URL] 換成 Nginx 的對外網址:

    const src = new URL(url.pathname, "https://img-origin.example.com")
    
  2. 在 Cloudflare Dashboard 建立 Worker,貼上 worker/index.js 全文並部署

  3. 為 Worker 綁定自訂網域(如 img.example.com),前端改用該網域讀圖

驗證

curl -sI "https://img.example.com/c/img/blog/a.jpg?w=800" \
  | grep -iE "cf-cache-status|x-query-string"

第一次為 MISS,相同 URL 再次請求為 HIT。

相關頁面

EN