[1068145 views]

[]

[toggle ads]

Odi's astoundingly incomplete notes

New entries | Code

Set your HTTP cache headers correctly

I see sites often disable caching of resources completely with really bad headers like:
Cache-Control: no-store, no-cache, must-revalidate
Expires: Wed, 4 Jun 1980 06:02:09 GMT
Pragma: nocache

It makes a lot more sense to let the client cache and tell it to check if the resource has been modified in the mean time. The easiest way to do that is to pass the Last-Modified header together with:
Cache-Control: max-age=0, must-revalidate
This will enable caching in the browser and the browser will request the resource with the If-Modified-Since header. The server will respond with 304 Not Modified if the resource's last-modified date is still the same, saving the transfer. If you need more control over the content of the resource and a last-modified date is not enough or can not easily be given, you can set the ETag header. ETag is a hash or version number of the content and changes as the resource's content changes. But careful: ETag may change with the Content-Encoding (compression). Carefully test if it behaves correctly with your gateway (reverse proxy).

Maybe this practice comes from bad defaults in Apache. I have not seen any default Apache config that sets sensible Cache-Control. Therefore no header is sent and browsers cache such responses forever, not even clicking the Reload button will fetch it again. This of course makes developers take the simple but radical option to disable caching.

A much better default for Apache is:
Header set Cache-Control "max-age=0, must-revalidate"



posted on 2019-05-06 11:02 CEST in Code | 0 comments | permalink