Cache static files of MEAN stack with Nginx
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:
offis for no caching control header — everything you don’t want to be cachedepochis a special value, it specifically ask the browser to always ask if the website itself is up to datemaxset the cache to the maximum that a browser can handle (with Firefox it’s315360000 seconds)7dis a custom value, it means 7 days off course, you can use whatever you wantmis for minutes,Mfor 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)Expiresis 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!
