How to cache an HTML response in CloudFlare but not browser

(I was going to ask a question about this but eventually pieced together a solution from various doc pages. Since it’s not obvious how to do this I thought I would share the answer.)

Goal

  • Benefit from CDN performance by caching an html page with Cloudflare, but:
  • Don’t allow browsers to cache the page

Cloudflare doesn’t normally cache html responses, which means the response time may be slow as the origin server will be contacted on every request.

It’s not too hard to get Cloudflare to cache HTML in the CDN layer, but without some extra configuration the HTML will be cached by browsers as well (for 4 hours be default). This means that if a user visits your page, and then you update it and they visit it again before their browser cache expires, they will not see the updated page.

So how do you cache a HTML response in Cloudflare but not the browser?

1 Like
  1. Ensure the page is sent from origin server with a header like below. s-maxage is the number of seconds Cloudflare should cache the page for, max-age is how long the browser should cache it for.
    Cache-Control: s-maxage=86400, max-age=0
    
  2. Tell Cloudflare to respect your origin server cache settings instead of using their own. Update the setting:
    Caching > Browser Cache Expiration: Respect Existing Headers
    
  3. Set up a Cloudflare page rule to match your html file/s. Example for a home page:
    yoursite.com/
    Cache Level: Cache Everything, Origin Cache Control: On
    

That’s working lovely for me, and giving me very snappy loading times for jonomenz.com

4 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.