Cloudflare Worker

Last updated


This page explains how worker/index.js caches images at the Cloudflare edge and how to deploy it.

Behavior


ItemBehavior
Accepted pathsEnding in .jpg, .jpeg, .png, .webp, .svg (case-insensitive); everything else returns 400 with text 400
ForwardingKeeps the original path and every query parameter, forwarding to the [URL] origin
Cache keyA Request for the full origin URL with X-Custom-Cache-Key: {query string or no-query}
Storagecaches.default; the response is rewritten with Cache-Control: public, max-age=604800 and stored via event.waitUntil(cache.put(...))
Response headersCF-Cache-Status: HIT / MISS, X-Query-String: {query string or none}

Deployment


  1. Replace [URL] in worker/index.js with the public Nginx origin:
    1. const src = new URL(url.pathname, "https://img-origin.example.com")
  2. Create a Worker in the Cloudflare Dashboard, paste the full worker/index.js, and deploy
  3. Bind a custom domain to the Worker (e.g. img.example.com) and point the frontend at it

Verify


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

The first request is a MISS; repeating the same URL returns HIT.

中文