I have run some tests for a website involving how dynamic content (via PHP/nginx in this case) gets cached by various browsers.
I came to the conclusion that, by default, php files are never EVER pulled from cache, even in mobile browsers, even if in the response there is no Cache-Control
nor Expires
parameter, even if i don't send POST requests and i just follow a link to the page. They are always redownloaded. By contrast, css/js/image files are fetched from cache.
This is good for me, because i want dynamic html to always hit the backend and have a caching mechanism either in the form of Varnish or my own php/filesystem implementation.
Is this usually expected behavior by default? I'm using session cookies by the way.
First of all: I'm not an expert and there is most likely more things you could add to the topic than I will do now, but it should give you a basic understanding of how it works.
CSS, Images and Javascript files are (usually) served directly by the webserver without hitting any php script. Therefore the webserver handles caching itself for these files.
For PHP content the webserver invokes your php script and returns status code 200 (if there is no error or if it is not explicitly specified differently in the script).
Now see this link: Caching Tutorial
There it says:
If no validator (an ETag or Last-Modified header) is present on a response, and it doesn't have any explicit freshness information, it will usually — but not always — be considered uncacheable.
That said, the webserver will not add these headers to php responses. But it WILL add them to static resources like images, css, js.
So for future requests to your website, the browser knows (because of these headers) that the site itself is not cachable, but the image is.
If you request the website a second time, the client would just normally request the php script and again get the normal response, since there were no caching information included in the original response (nothing special here).
Now the article above says:
When a cache has a representation stored that includes a Last-Modified header, it can use it to ask the server if the representation has changed since the last time it was seen, with an If-Modified-Since request.
So basically the browser would ask the webserver if the image changed, and if it did not, the server would return a "304 Not Modified" response, without adding the actual image to the response (<= this is caching).
As I said before, a php script never returns this status code if not explicitly set. So after covering the basics we can come to the important part: ;-)
tl;dr or "How to cache PHP pages"
You should probably read the section "Writing Cache-Aware Scripts" of the article above first.
However one solution would be:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With