Blog

What and How: NGINX – Browser caching and gzip compression

While serving static content from a server to browser If performance is very slow, we can optimize it by implementing below 2 methods.

1. Enable GZIP compression which will serve files of the specified format by zipping it between server and browser. This minimizes web serving time.  
2. Enable images caching to 6 days or more If you want NGINX to cache images in it and serve faster. 
Let’s see how can we achieve both of above.

In your default NGINX configuration file, where all rules are written, check for following

location ~* \favicon.ico$ {
        expires 6d;
    }

    location ~ \.css {
        root /var/www/html;
        add_header  Content-Type    text/css;
        expires 6d;
    }

    location ~* \.js {
        root /var/www/html;
        add_header  Content-Type    application/x-javascript;
        expires 6d;
    }

    location ~* \.png|jpeg|jpg {
        root /var/www/html;
        add_header  Content-Type    image/png;
        add_header  Content-Type    image/jpeg;
        add_header  Content-Type    image/jpg;
        expires 6d;
    }
    location ~* \.svg {
        root /var/www/html;
        add_header  Content-Type    image/svg+xml;
        expires 6d;
    }

Here in every new location blog, we have added “expires 6d”

It will cache those objects in NGINX after once served, and next time when a request arrives it can serve from caching, thus provide faster results.
It will re-cache after 6 days.

2. To enable gzip compression, add the following file at /etc/nginx/conf.d/gzip.conf directory

gzip on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_min_length 256;
gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/json application/xml application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_vary on;

It will compress content of above-mentioned content types when communicating between server and browser, thus serves faster with compression applied.

Do try to apply this and let us know how much faster results you were able to get! Do Comment below.

Leave a Comment