Enable Compression in Nginx

Enable Compression in Nginx

Category : How-to

Get Social!

nginx-logoEnabling web content compression is one of the simplest ways to save bandwidth and, for some users, speed up the time it takes to serve a page. All modern browsers support content compression and the CPU overhead for clients is a thing of the past.

Compressing content on your server however, can be CPU intensive and something you may have to plan for. Generally, compressing anything is a trade off between size of the content and the CPU cycles required in compressing it. With Nginx, content that has compression enabled has to be sent through a gzip algorithm to compress it before it’s sent to the client.

Some content does not lend itself to compression in this manner. such as images and zip archives. This is because this content has already been compressed and compressing further will have little or no result. In fact, certain types of content can even end up larger after compression. Due to this, we only tend to compress content such as HTML, CSS, JS, XML and other text based content.

The below steps will enable gzip compression for the entire Nginx server – that includes all server{} tags listed in the sites-enabled config.

Create a new file called compression.conf in the Nginx conf.d directory. If this directory doesn’t exist on your Nginx installation, you can add this to the bottom of nginx.conf.

vi /etc/nginx/conf.d/compression.conf

Add the below text and save and close the file.

gzip on;
gzip_http_version 1.1;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xm
l+rss text/javascript application/javascript text/x-js;
gzip_buffers 16 32k;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";

I won’t detail each line in the file, but two of the interesting attributes are:

  • gzip_comp_level – this is the compression level that gzip will apply to the content, between 1 and 9 where 1 is the lowest compression and 9 is the highest. Again, this is a trade of between CPU (and therefore time to compress the content) and the resulting file size. 5 – 7 is usually considered a sensible range for this value.
  • gzip_types – this is the MIME type of content that may be compressed. As you can see, each entry here is text based with no images/ zip files listed.

Reload the Nginx config for the changes to take effect.

service nginx reload


Leave a Reply

Visit our advertisers

Quick Poll

Do you use ZFS on Linux?

Visit our advertisers