How to cache an HTML response in CloudFlare but not browser

#1

(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
Is s-maxage used by proxies or just reverse proxies?
#2
  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

3 Likes
closed #3

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