Bypass Cache Everything with PHP


Im using a Cache Everything rule to cache a lot of json request to my server, and I works amazing.
But some times my server don’t have data to show at the moment, and here is my problem: the json is showing a “error msg” and that’s also been cached.

So can I via PHP bypass the Cache Everything rule ? Maybe with a different header ?


Hi Sandro,
Thanks - but my problem is that I want to Cache Everything - expect when the php/json make an error.
Hope it makes sense

So you even want to cache the PHP output? In that case that wont be possible. You cant cache things but at the same time still have requests sent to your origin.


Result: OK = Cache

Result: Error = By Pass Cache

Second try loading:
Result: OK = Cache

So I want to load the page, and IF it work than Cache - but if there is an error, than bypass cache until the url loads ok again.

So you only want to cache it if the first request does not throw an error?

In that case you can still implement the logic from the linked thread and simply omit the caching header when there was no error during the request.

Yes exactly.
So you mean I should set the page rule to “Bypass” ?

And then add on errors:
header(“Cache-Control: no-cache, must-revalidate”);

And success
header(“Cache-Control: max-age=XX 1 day XX”);

A rule is not involved here. You need to check out the linked thread.

Yes thanks - but I can’t find any information on how to controle cache by php headers on that link.
Sorry im not so technical about cache, just need to see an example :wink:

There is no concrete information on that as that is PHP specific and hence related to software development and outside the scope of the forum here.

You simply need to make sure you send the caching header only as long as you have an error.

Okay, but im not sure how to make Cloudflare act like “Cache everything” on success.

I try´d this, but it don’t work:

$data 	= $_GET["data"];

	$ts = gmdate("D, d M Y H:i:s") . " GMT";
	header("Expires: $ts");
	header("Last-Modified: $ts");
	header("Pragma: no-cache");
	header("Cache-Control: no-cache, must-revalidate");

	$seconds_to_cache = 60;
	$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
	header("Expires: $ts");
	header("Pragma: cache");
	header("Cache-Control: max-age=$seconds_to_cache");

echo "NOW: ". gmdate("D, d M Y H:i:s");

That is a question for StackOverflow at this point I am afraid.

If you have a cache everything rule it will always cache and you dont need to make it do it.