Enable gzip in Nginx

by Scott Hebert

nginx logo -leftIf you have ever used any tool to optimize a web page, you know that compressing the return traffic to the client is a big win. In nginx, this is done with the gzip module. The easiest thing to do is add gzip on; to the http stanza in your nginx.conf and be done with it. By default, this will enable minimal compression for all files returned with type text/html. This is great, but it does not really cover all the traffic you may be returning to the client. Specifically, there are big gains to be had by compressing CSS, Javascript, and XML traffic. Below, I have included an example configuration that does a better job of compressing traffic than the default.


There is no sense in compressing files that are already small. The size gains are outweighed by the performance hit of calculating the compression. The default for this is 20 bytes, but considering the abundance of broadband Internet, something larger seems more reasonable.


The default compression level is only 1. This is probably plenty, but considering the speed of modern CPUs, it seems reasonable to up the compression level a bit. This is one that you will need to tweak based on your server configuration. I have not had any problem setting this to 6, but your mileage may vary.


By default, the gzip module disables compression for requests that are made via a proxy server. This is actually a good thing for proxy servers as it should make it easier to cache. If you are the person running the proxy server in front of nginx, you almost certainly want to leave this at the default. Otherwise, there are a myriad of options available here.


These are the MIME types that you want compressed. As I previouslly mentioned, only text/html is compressed by default. Not only have I added plain, CSS, Javascript, and XML, but I have included GIFs and ICOs as well. This option accepts several parameters, but I have divided mine up a bit for readability.


Finally, this option allows you to disable gzip compression for certain User-Agents. Older versions of Internet Explorer, for example, do not handle compressed data very well.

That should just about cover it. And remember: COMPRESS ALL THE THINGS.