How to bypass cloudflare caching like reddit does

There are two key ways of doing this with CloudFlare:

  • In CloudFlare you can set a page rule to avoid caching files of your choice.
  • You can serve no-cache headers which CloudFlare will respect.

In order to set-up a Page Rule

  1. Go to your CloudFlare dashboard and select Page Rules
  2. Add a Page Rule which matches *yourdomain.com/*.html
  3. Set cache level to bypass
  4. Save and deploy

Page Rule with Cache Level Bypass

Set Cache Headers

CloudFlare's Help Centre explains how to control cache through the headers sent from the origin:

The second way to alter what CloudFlare will cache is through caching headers sent from the origin. CloudFlare will respect these settings (but only for files with the extensions that we cache by default), unless a Page Rule is set to cache everything and an edge cache expires TTL is set. Here are the caching headers we consider:

  • If the Cache-Control header is set to "private", "no-store", "no-cache", or "max-age=0", or if there is a cookie in the response, then CloudFlare will not cache the resource.
  • Otherwise, if the Cache-Control header is set to "public" and the "max-age" is greater than 0, or if the Expires headers are set any time in the future, we will cache the resource.

Note: As per RFC rules, "Cache-Control: max-age" trumps "Expires" headers. If we see both and they do not agree, max-age wins.

In PHP you can implement this using the header function as follows:

header("Cache-Control: no-cache, must-revalidate");