Browser cache: Cache-Control, ETag and file versions
The fastest file is the one that does not have to be downloaded at all. How to tell the browser with the Cache-Control header what it may store and for how long, how validation with ETag and the 304 response works and how to make sure that visitors get the new CSS and JavaScript after a change to the site.
How the cache works
The browser stores downloaded files. When it needs a file again, it decides based on the headers the server sent with it:
- the file is still fresh (the time from max-age has not passed) – it uses it without a single request to the server;
- the file is stale – it asks the server whether the file has changed. It sends its ETag or the date of the last change. The server responds either with 304 Not Modified without content (the browser uses the stored copy) or with 200 and the new content.
Validation saves data transfer, but not the wait for the response. A long freshness helps the most.
The Cache-Control header
- max-age=604800 – the file is fresh for 604,800 seconds (a week);
- no-cache – it may be stored, but the browser must ask the server before each use. It does not mean “do not store”;
- no-store – do not store at all (pages with personal data, administration);
- private – only the browser may store it, not shared caches between it and the server (proxies, CDN); public – anyone may;
- immutable – the file never changes at this address, so the browser does not have to validate it even when the page is reloaded. It is suitable for files with a version in the URL (see below). Firefox and Safari support it. Chrome does not know it, but it does not validate fresh files of the page on reload at all.
When the server does not send any freshness time, the browser estimates it itself – usually as a tenth of the time since the last change of the file. That is why it is better to set the time explicitly.
Settings in .htaccess
On an Apache server, the headers for static files are set in the .htaccess file. With the mod_headers module:
<IfModule mod_headers.c>
<FilesMatch "\.(css|js)$">
Header set Cache-Control "public, max-age=604800"
</FilesMatch>
<FilesMatch "\.(jpe?g|png|gif|webp|avif|svg|ico|woff2)$">
Header set Cache-Control "public, max-age=2592000"
</FilesMatch>
</IfModule>
Styles and scripts are fresh for a week, images and fonts for 30 days. The same can be written with the mod_expires module, which also sends the older Expires header with a date (when both are present, Cache-Control applies):
<IfModule mod_expires.c> ExpiresActive On ExpiresByType text/css "access plus 1 week" ExpiresByType application/javascript "access plus 1 week" ExpiresByType text/javascript "access plus 1 week" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month" </IfModule>
The file type is determined by the extension according to the server settings. Depending on the Apache version, JavaScript has the type application/javascript (older) or text/javascript, which is why both are in the example. Which module the server has can be seen from the response headers (see below) – when a module is missing, the contents of IfModule are skipped. On hosting where nginx runs in front of Apache, the cache of static files is often set by nginx and turned on in the control panel of the hosting. More about .htaccess is in the How .htaccess works article.
ETag, Last-Modified and the 304 response
Apache adds an ETag (a fingerprint of the size and modification time) and Last-Modified to static files by itself. When validating, the browser asks like this:
GET /css/styles.css HTTP/1.1 If-None-Match: "57ec-65cc18d9acbae" If-Modified-Since: Thu, 01 Oct 2026 06:30:34 GMT
and when the file has not changed, it gets a short response without content:
HTTP/1.1 304 Not Modified ETag: "57ec-65cc18d9acbae"
PHP output gets no ETag – the script runs every time. For content that changes rarely and costs something to produce (a list of articles in JSON, RSS), you can send the ETag yourself and return 304 when it matches:
<?php
function etag_matches($etag)
{
$sent = $_SERVER['HTTP_IF_NONE_MATCH'] ?? '';
foreach(explode(',', $sent) as $e)
{
$e = preg_replace('~^W/~', '', trim($e)); // weak ETag – nginx after compression
$e = preg_replace('~-(gzip|br)"$~', '"', $e); // suffix added by Apache after compression
if($e === '*' || $e === $etag) return true;
}
return false;
}
$content = json_encode(array('articles' => array('Browser cache', 'Images on the web')));
$etag = '"'.md5($content).'"';
header('Cache-Control: no-cache');
header('ETag: '.$etag);
if(etag_matches($etag))
{
http_response_code(304);
exit;
}
header('Content-Type: application/json; charset=utf-8');
echo $content;
- the ETag is in quotes, the browser returns it in the If-None-Match header (PHP reads it as $_SERVER['HTTP_IF_NONE_MATCH']) and it may send several of them separated by commas;
- when the server compresses the response, it modifies the ETag: Apache adds the suffix -gzip or -br inside the quotes, nginx marks the ETag as weak with the W/ prefix. Without the adjustments in the function, the ETag would never match;
- no-cache makes sure that the browser asks every time – it still saves transferring the content;
- PHP produces the content anyway here, only the transfer is saved. When producing it takes long, a cache on the server helps, see Server speed.
Instead of an ETag, the date of the last change can be used: the Last-Modified header in the form gmdate('D, d M Y H:i:s', $time).' GMT' (the gmdate() function) and a comparison with $_SERVER['HTTP_IF_MODIFIED_SINCE'] using strtotime().
File versions in the URL
A long freshness brings a problem: after a change to the CSS, visitors have the old version in their cache. The solution is to add a version to the address, for example styles.css?v=1.1. For the browser it is a different address, so it downloads the file again. Rewriting the version by hand is no longer needed when PHP takes it from the time of the last change of the file:
<?php
function version($file)
{
return $file.'?v='.filemtime(__DIR__.'/'.$file);
}
?>
<link rel="stylesheet" href="<?= version('css/styles.css') ?>">
<script src="<?= version('js/scripts.js') ?>" defer></script>
<link rel="stylesheet" href="css/styles.css?v=1791590400"> <script src="js/scripts.js?v=1791590400" defer></script>
The filemtime() function returns the time of the last change as a Unix timestamp. When the file changes, the address changes too. Files that are loaded only with a version can then be fresh for a whole year and immutable – in the first .htaccess example, it is enough to write "public, max-age=31536000, immutable".
What does not belong in the cache
Send pages with personal data, the shopping cart or the administration with Cache-Control: no-store. PHP does this by itself for pages with a session: session_start() with the default setting (session.cache_limiter = nocache) sends the headers Cache-Control: no-store, no-cache, must-revalidate, Pragma: no-cache and Expires with a date in the past. That is why pages of sites with sessions are not stored, even when they could be.
How the cache behaves is shown by the developer tools (F12), the Network tab: the size column shows “(memory cache)” or “(disk cache)” for files from the cache and the status 304 for validated files. Ticking “Disable cache” turns the cache off while debugging.
Related articles:
Compression and data transfer: gzip, Brotli and HTTP/2
Security headers and HTTPS
How .htaccess works
Loading CSS, JavaScript and fonts