Strong caching with NGINX
2nd February 2014 | by Adam Beres-Deak | nginx, caching
Strong caching is very important nowadays since it can reduce page load times for the users (and eventually it can also reduce network transfer costs for the publishers). Here we see a simple example how to do it with NGINX for static files like css, JavaScript and images.
server {
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
root /var/www/mysite;
expires max;
add_header Cache-Control "public";
access_log off;
break;
}
}
Of course after modifying the config file we have to reload the configs (e. g. on Ubuntu we have to type sudo /etc/init.d/nginx reload
)
There are a few things to note here:
- we set the "expires" header to max age, which means these resources can stay in the browser cache 'forever'
- we are setting the "Cache-Control" header to "public", which means that the resource "may be cached in public shared caches"
- we turn off access logging here, because these requests are in many cases not that important
- if you set expiration to max-age, you have to be sure that the requested resources really never change (some kind of cache busting)
- these settings can live in the
location
section or in theserver
section of an nginx config file
Have you already enabled strong caching for yout asset files?
Update: Maybe you noticed the lookahead in the regex. It has a reason to be there: this way the regex engine doesn't create a capture group (no $1) so it has better performance.
Latest blog posts
Displaying icons with custom elements 14th October 2015
Plain JavaScript event delegation 26th January 2015
After the first year of blogging - what happened on my blog in 2014? 1st January 2015
Better webfont loading with using localStorage and providing WOFF2 support 18th December 2014