Cloudflare Worker
Last updated
This page explains how worker/index.js caches images at the Cloudflare edge and how to deploy it.
Behavior
| Item | Behavior |
|---|---|
| Accepted paths | Ending in .jpg, .jpeg, .png, .webp, .svg (case-insensitive); everything else returns 400 with text 400 |
| Forwarding | Keeps the original path and every query parameter, forwarding to the [URL] origin |
| Cache key | A Request for the full origin URL with X-Custom-Cache-Key: {query string or no-query} |
| Storage | caches.default; the response is rewritten with Cache-Control: public, max-age=604800 and stored via event.waitUntil(cache.put(...)) |
| Response headers | CF-Cache-Status: HIT / MISS, X-Query-String: {query string or none} |
.avif and .pdf are not in the accepted list: uploaded PDFs cannot be fetched through the Worker, while AVIF output still works by requesting the original extension (e.g. .jpg?t=avif).
Deployment
Replace
[URL]inworker/index.jswith the public Nginx origin:const src = new URL(url.pathname, "https://img-origin.example.com")Create a Worker in the Cloudflare Dashboard, paste the full
worker/index.js, and deployBind a custom domain to the Worker (e.g.
img.example.com) and point the frontend at it
Verify
curl -sI "https://img.example.com/c/img/blog/a.jpg?w=800" \
| grep -iE "cf-cache-status|x-query-string"
The first request is a MISS; repeating the same URL returns HIT.
Related Pages
- How the four caches relate: Caching Layers
- Origin configuration: Nginx