If 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.
gzip on;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css;
gzip_types text/xml application/xml;
gzip_types image/x-icon image/gif;
gzip_types application/javascript application/x-javascript;
gzip_disable msie6;
gzip_min_length
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.
gzip_comp_level
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.
gzip_proxied
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.
gzip_types
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.
gzip_disable
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.