Caching HTTP Headers, Cache-Control: max-age

Caching speeds up repeated page views and saves a lot of traffic by preventing downloading of unc hanged content every page view.
We can use Cache-Control: max-age=… to inform browser that the component won’t be changed for defined period. This way we avoid unneeded further requests if browser already has the component in its cache and therefore primed-cache page views will be performed faster.
Modern browsers able to cache static files even without any cache control headers using some heuristic methods but they will do it more efficient if we define caching headers implicitly.

For Apache2 you can enable max-age using mod_expires:


ExpiresActive On
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"

For Lighttpd there is mod_expire module. Enable it in server.modules section:

server.modules = (
...
"mod_expire",
...
)
Then add following directives for directories with static files:
$HTTP["url"] =~ "^/images/" {
expire.url = ( "" => "access 30 days" )
}

Max-age for Nginx server can be enabled using ngx_http_headers_module:

expires max;

Now web server sends the caching header for static files:

Cache-Control: max-age=2592000

In case of design change we should prevent using outdated content that browsers have in their caches. This can be done by adding file versions to filenames:

script.js -> script1.js -> script2.js -> ... etc



( Read more )