Different Cache-Control header for R2 200-OK vs !200-OK?

Hi there

Is it possible to set a different Cache-Control header for an R2 response, one for HTTP 200 OK, and another for everything else?

I ask, as I’ve successfully got an R2 Cache-Control header of “max-age=31536000, immutable” set using a “Modify Response Header” Transform Rule on the fronting domain (I’m storing static images). However, I’ve just observed this header being added to an HTTP 404 response, which is not good. I obviously don’t want this on HTTP 500 either! For non-200 OK responses, Cache-Control: “'no-store” makes sense.

The best approach I’ve seen is described in the linked post, where the Cache-Control header is actually set on the R2 object meta-data itself, which hopefully R2 honours: https://community.cloudflare.com/t/r2-with-custom-domain-setup-object-not-found-404-returns-cache-header-with-max-age-of-24-hours-rather-than-a-short-expiry/432485/12?u=greg66

I had hoped to find a solution that could be set via the Cloudflare UI, as that would be more dynamic. However, I’ll settle for the static meta-data solution if it works…

Many thanks in advance

Greg

I think setting “Status code TTL” should work, under Cache Rules:

I want R2 to not cache 404s, for example. I haven’t tested this yet though.

1 Like

Hi @archon810, and thanks for the response.

I don’t believe any of the Cache Rules will fix this - even one mentioning a status code - as they are focused on what Cloudflare caches.

I’m interested in the user’s browser TTL, which is determined by the Cache-Control header. The most plausible option might be the Browser TTL option, though I’m currently unclear how it behaves for 200 and non-200 status codes.

I have managed to get a Cache-Control: "max-age=31536000, immutable” header returning for R2 objects with 200 ok, and no Cache-Control header for non-200 ok. I used the approach I mentioned above by setting the Cache-Control value on the r2/s3 object metadata.

However, I’d still prefer a more dynamic solution configurable via the Cloudflare dashboard

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.