How to enable Compression in Nginx

If you are using Nginx webserver, you have to try this out. I started exploring for this option when I faced slowness in rending the pages in one of the applications. When I checked the backend services, the web service API was given the responses quickly, but the page was taking more time to load. On further inspection, I figured out that the API was sending a a data of size 5 MB. So the browser will first download this data and this speed depends on the bandwidth.

I explored further and figured out the way of compressing API body using the webserver. This will speed up the API calls as the data transferred over the network will be very less. In my case, the 5 MB data became few KBs (size of compressed data). This will get extracted quickly in the browser and it gets rendered in the screen.

The required configurations are pasted below for quick reference.

Make the changes in the config file /etc/nginx/nginx.conf. Add the following content to the nginx.conf file.

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";

 

The explanation of each of the parameters are given below.

  • gzip on; – enables gzip compression in nginx
  • gzip_vary on: – tells proxies to cache both compressed and normal versions of a resource
  • gzip_types – The type of files that can be compressed
  • gzip_disable “MSIE [1-6]\.”;  – Disable compression for Internet Explorer versions 1-6
  • gzip_min_length 1024; – Nginx will compress the files greater than this size and it will not compress anything less than this size.
  • gzip_proxied – compress data even for clients that are connecting via proxies

 

This is one of the way to improve the performance of APIs. The developers can focus on enhancing their logic and the admin or DevOps engineer can focus on enhancing the web server with optimal configuration. There are so many tricks and magics we can do in the web server. I will try to post some of those in my blog.

Hope this helps. 🙂 . Please comment if you face any issues.

About amalgjose
I am an Electrical Engineer by qualification, now I am working as a Software Architect. I am very much interested in Electrical, Electronics, Mechanical and now in Software fields. I like exploring things in these fields. I love travelling, long drives and music.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: