Cache static files of MEAN stack with Nginx

Xavier Coiffard
Sep 6, 2018 · 2 min read

I setup a MEAN stack (Mongo + Express + Angular + nodejs) and needed to speedup the loading of the application with caching.

Caching is probably one of the most important thing to do to improve your performances and SEO. My apps are powered with Nginx, because it’s fast & simple, so I started to look for a way to install cache with nginx.

The dead-end

The first thing you will find if you look for caching static files with nginx is :

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
expires 30d;
add_header Vary Accept-Encoding;
access_log off;
}

Just add this piece of code BEFORE any location in your server configuration and it should works.

In my case it did not.

The real — more complex — solution

Instead of using the expires as if we will use it with map .

Here is how I did it:

Open your server configuration and add on top of it:

# Expires map
map $sent_http_content_type $expires {
default off;
text/html epoch;
text/css max;
application/javascript 7d;
~image/ max;
}

This way you have a very precise way you cache static files, just provide the MIMEType and the length you want to cache them, and you’re good!

Nginx is very powerful for setup the length of caching files:

  • off is for no caching control header — everything you don’t want to be cached
  • epoch is a special value, it specifically ask the browser to always ask if the website itself is up to date
  • max set the cache to the maximum that a browser can handle (with Firefox it’s 315360000 seconds )
  • 7d is a custom value, it means 7 days off course, you can use whatever you want m is for minutes, M for months… Here is the doc about nginx time

Then in your server block:

server {
listen 80;
expires $expires;

And then of course, restart your webserver:

sudo systemctl restart nginx

Test it!

Open your website, check the network tab in the developer console and you should see something like :

The 2 important headers here are:

  • Cache-Control : We can see here the 7 days (604800 sec)
  • Expires is the date when my browser will ask again to the server a new version of the files. Otherwise it will use the one stored in his cache.

You can also check the loading time, it should be way better!

Xavier Coiffard

Written by

I build apps, teams and try to keep the fun alive!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade