Jun 11. 2018 · by Helge Sverre

Leveraging Browser Caching on Nginx

Leverage Browser Caching is a word you probably have seen if you've run your website through either Google Page speed, Pingdom Tools or GTMetrix (my favorite)

What this sophisticated sounding sentence actually means is... *drum roll* add Cache expires headers to your asset files (js, css, images etc) so the browser knows to cache them for the future, modern browsers do this by themselves automatically without the cache headers, but eh, we need that higher score on dem dar speed-tools!

Throw this inside your server block, adjust the expire date if 7 days (7d) is too long or short for your use case.

nginx configuration file
location ~*  \.(jpg|jpeg|png|gif|svg|ico|css|js)$ {
    expires 7d;

The config above will add an expires header to all jpg, png, gif, svg, ico, css and js files of 7 days in the future.

And that is pretty much it for Nginx, re-check your site in whatever speed testing tool you prefer, and reap the fruits of your labor.


I tried it out on my personal website (https://helgesver.re) and here is a before and after.


And here is the score after applying the cache header

Boom, from 88 to 98 just from that simply change, go fourth and leverage them browser caches.