Caching static files in Nginx

A guide to configuring static file caching in the user's browser cache.

The Expires header is responsible for how long the cache is up to date, and the browser can use cached resources without asking the server for a new version

In a text editor open nginx.conf

  • on Linux - /etc/nginx/

find the server {} configuration block for your virtual host. In this configuration block there is a section location for handling static documents

The location block will end up looking something like this:

location ~* ^.+.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {
                        root /var/www/username/data/www/usernamesite.ru;
                        access_log /var/www/nginx-logs/usernamesite isp;
                        access_log /var/www/httpd-logs/usernamesite.ru.access.log ;
                        error_page 404 = @fallback;
                        expires 7d;
}

where expires 7d is the number of days how long the cache of static files should be kept on the user's computer. If you do not make changes in css, js, files of your site and do not change the pictures, it makes sense to increase this parameter up to several months or even a year.

Second option is to teach panel to specify expires parameter for static in all virtual servers in nginx configuration file. To do this, create file /usr/local/ispmgr/etc/server.templ with the following contents:

location ~* ^.+.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {
                        expires 7d;
}

Now turn on GZIP compression for static files

GZIP compression saves traffic and increases page load speeds.

How to enable GZIP for static files in NGINX

server {
    ....
    gzip on;
    gzip_disable "msie6";
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
}
Updated at:
2/25/2019, 12:02
Need help?Our engineers will help you free of charge with any question in minutesContact us