Setting cache-control to images served through Cloudflare Images

There is always a big challenge to set the cache-control of image served via CDN's (content delivery networks). Cloudflare has a feature which is somewhat hidden, but when you discover this, you can change the way header responses are served to the browser.

Typically most CDN's will deliver cache-control at 30 days, sometimes 4 hours. Trying to override this using server headers or htaccess rules does not help.

Cloudflare has an option called Transform Rules, described below.

Use Transform Rules to transform your traffic. This includes URL NormalizationURL Rewrites, and Header Modifications. Transformed traffic is then used as input for other Cloudflare products.

You can apply this to local images and or CDN images if the CDN images are serving through a domain hosted on Cloudflare's network (ie. using the orange cloud).

If your URL has the following format:[imagepath]

Once we know the path, we can use a transform rule to change the HTTP response header. We are assuming you already have a Cloudflare account.
Navigate to Rules > Transform Rules >  Create transform rule.

Follow this screenshot to add HTTP Response Header Modification rule for cache-control. In the example below, we have added a 1 year (max-age=31536000) cache to images served via Cloudflare Images.

Verifying the cache-control changes

Once the rule has been added, it takes a few seconds to update across Cloudflare.

To verify a resource's cache-control header is set as expected, check its HTTP header data:

  1. In chrome, open Developer Tools
  2. Click on network (at this point you may need to reload the page to see the URL's)
  3. At the top filter by Img so you see all the images loaded, select an image
  4. Click the URL (or image) of the request, under the Name column of the Requests table.
  5. Click the Headers tab and select Response Headers.
    You should see the following change in your cache cache-control