This site sat behind Cloudflare for a while before I checked what it was actually caching. The answer was images, CSS and JavaScript. Every page still made the trip to my server in New York, whether the visitor was in New Jersey or Singapore.
That’s the default, and it surprises people. Cloudflare caches files by extension, and an HTML page from WordPress isn’t on the list. You can see it in the response headers.
curl -s -o /dev/null -D - https://example.com/ | grep -i cf-cache-status
# cf-cache-status: DYNAMICDYNAMIC means Cloudflare passed the request straight through. What you want on a page is HIT.
Cloudflare sells a fix called APO, and there are plugins that do the same job. I wrote about a hundred lines of PHP and one cache rule instead, mostly because I wanted to know exactly which pages were being cached and why.
The Risk With Caching Pages
WordPress serves different HTML at the same URL depending on who’s asking. Log in and the page grows an admin bar. Leave a comment and the form remembers your name. If Cloudflare stores one of those and hands it to the next visitor, you’ve published your admin bar to the world.
So I didn’t want a rule that says “cache everything except the things I remembered to exclude”. I wanted WordPress to mark each page it knows is safe, and Cloudflare to cache only what’s marked.
WordPress Marks the Safe Pages
The mark is a Cache-Control header. s-maxage speaks to shared caches like Cloudflare and max-age speaks to browsers, so one header can tell Cloudflare to keep a page for a day while browsers ask again every time.
add_action( 'template_redirect', function () {
if ( headers_sent() || ! my_edge_cacheable() ) {
return;
}
header( 'Cache-Control: public, max-age=0, s-maxage=' . DAY_IN_SECONDS );
}, 999 );
function my_edge_cacheable() {
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ( ! in_array( $method, array( 'GET', 'HEAD' ), true ) || ! empty( $_GET ) ) {
return false;
}
if ( is_user_logged_in() || is_404() || is_search() || is_preview() || is_feed() ) {
return false;
}
if ( is_singular() && post_password_required() ) {
return false;
}
foreach ( array_keys( $_COOKIE ) as $name ) {
if ( preg_match( '/^(comment_author|wordpress_|wp-postpass|wp-settings)/', (string) $name ) ) {
return false;
}
}
return true;
}Anything that fails a check gets no header at all. That covers logged-in views, searches, previews, password-protected posts, any URL with a query string, and anyone carrying a comment cookie.
Keeping max-age at zero matters more than it looks. I can empty Cloudflare’s cache whenever I like, but I can’t reach into a visitor’s browser. If browsers held pages for a day, an edit would take a day to show up for anyone who’d already visited.
The Cache Rule
In the Cloudflare dashboard this lives under Caching, then Cache Rules. It works on the Free plan. The rule has three settings.
- Cache eligibility is “Eligible for cache”.
- Edge TTL is “Use cache-control header if present, bypass cache if not”.
- Browser TTL is “Respect origin TTL”.
The Edge TTL setting is the one that makes the whole design work. A page without my header is never stored, so the PHP above is the single place that decides what’s cacheable.
The rule’s expression still screens out the obvious cases, as a second lock on the same door.
(http.host eq "example.com"
and http.request.uri.query eq ""
and not http.request.uri.path contains "/wp-admin"
and not http.request.uri.path contains "/wp-json"
and not http.request.uri.path contains ".php"
and not http.cookie contains "wordpress_logged_in"
and not http.cookie contains "wordpress_sec"
and not http.cookie contains "wp-postpass"
and not http.cookie contains "comment_author")The cookie lines do something the header can’t. When I’m logged in, Cloudflare skips its cache for me entirely, so I never get served the stored public copy of a page I’m trying to edit.
Purging When Something Changes
A page cached for a day is only acceptable if a change clears it straight away. Cloudflare has an API call for that, and it needs a token. Create one with a single permission (Zone, Cache Purge) limited to the one site, and keep it in wp-config.php, out of the repository.
function my_edge_purge() {
if ( ! defined( 'CLOUDFLARE_API_TOKEN' ) ) {
return;
}
wp_remote_post(
'https://api.cloudflare.com/client/v4/zones/' . CLOUDFLARE_ZONE_ID . '/purge_cache',
array(
'timeout' => 8,
'headers' => array(
'Authorization' => 'Bearer ' . CLOUDFLARE_API_TOKEN,
'Content-Type' => 'application/json',
),
'body' => '{"purge_everything":true}',
)
);
}
function my_edge_purge_later() {
static $queued = false;
if ( ! $queued ) {
$queued = true;
add_action( 'shutdown', 'my_edge_purge', 20 );
}
}
add_action( 'transition_post_status', function ( $new, $old, $post ) {
if ( ( 'publish' === $new || 'publish' === $old ) && is_post_type_viewable( $post->post_type ) ) {
my_edge_purge_later();
}
}, 10, 3 );Saving one post fires a lot of hooks, which is why the purge is queued and runs once when the request ends. transition_post_status also fires when WordPress publishes a scheduled post, so those clear the cache on their own.
The real version listens for more than posts. Approved comments, menus, category edits, a theme switch and the site title all change what’s on a page. My deploy script runs the purge too, because new CSS with old HTML is a bad afternoon.
I purge everything, every time. Purging single URLs sounds tidier, but one new post changes the home page, the archive, the category pages, the feed and the “related” list on other posts. On a site this size the cache refills as people visit, and I’d rather not maintain a list of every place a post can appear.
What Went Wrong
My first test said the header was missing. It wasn’t a caching problem. curl -I sends a HEAD request and my code only allowed GET, which is why HEAD is in the check above.
The purge failed with “Authentication error” on a token I’d just created. I’d restricted the token to my server’s IP address, which is good practice, and given it the IPv4 one. The server calls Cloudflare over IPv6. Adding the second address to the token fixed it. If you filter by IP, run this on the server before you fill in the form.
curl -s https://api64.ipify.orgCloudflare also challenged my own curl requests as a bot, so I couldn’t test from the terminal at all. The network tab in the browser’s developer tools shows the same headers.
Checking It Works
Load a page twice and look at cf-cache-status. The first request is a MISS, the second a HIT, with an age header counting the seconds since it was stored. Then try to break it.
- Add
?x=1to the URL. It should come backDYNAMIC. - Log in and load the home page.
DYNAMICagain, with the admin bar. - Open a private window afterwards and make sure there’s no admin bar in it.
- Edit a post, save it, and load it logged out. The change should be there on the first try.
If your server has its own page cache, as mine does with nginx, clear both when content changes. Otherwise Cloudflare empties its copy and promptly refills it with the stale page from the layer underneath.
Is it worth doing on a small site? I think so. A page that’s already cached comes from a Cloudflare data centre near the visitor and my server never hears about it. It’s also a hundred lines I can read from top to bottom, which is more than I can say for most caching plugins.
Leave a Reply