Skip to content

Enable Gzip Compression on Nginx Server

I tested this blog on GTMetrix to measure how fast this blog can be. The first test I run threw Grade D in Google PageSpeed Score and Grade B in Yahoo! YSlow Score. One area I should have it optimized is to enable Gzip Compression and to define “Specify a Vary: Accept-Encoding Header” in this blog’s header response.

This is what I have done so far :

Step 1 – I logged into my VPS.

Step 2 – I had to edit nginx configuration file :

nano /etc/nginx/nginx.conf

Step 3 – And then I looked for this line : gzip on. Most of the lines were commented (disabled) so I just need to enable it by removing the comment symbol (#). This is what I have :

gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

Step 4 – I save the configuration and restart Nginx :

sysctl restart nginx

Step 5 – I went back to GTMetrix and this what I got :

Performance Report

Anyway, here’s a nicer configuration with some explanations :

# Compression

# Enable Gzip compressed.
gzip on;

# Enable compression both for HTTP/1.0 and HTTP/1.1.
gzip_http_version  1.1;

# Compression level (1-9).
# 5 is a perfect compromise between size and cpu usage, offering about
# 75% reduction for most ascii files (almost identical to level 9).
gzip_comp_level    5;

# Don't compress anything that's already small and unlikely to shrink much
# if at all (the default is 20 bytes, which is bad as that usually leads to
# larger files after gzipping).
gzip_min_length    256;

# Compress data even for clients that are connecting to us via proxies,
# identified by the "Via" header (required for CloudFront).
gzip_proxied       any;

# Tell proxies to cache both the gzipped and regular version of a resource
# whenever the client's Accept-Encoding capabilities header varies;
# Avoids the issue where a non-gzip capable client (which is extremely rare
# today) would display gibberish if their proxy gave them the gzipped version.
gzip_vary          on;

# Compress all output labeled with one of the following MIME-types.
gzip_types
  application/atom+xml
  application/javascript
  application/json
  application/rss+xml
  application/vnd.ms-fontobject
  application/x-font-ttf
  application/x-web-app-manifest+json
  application/xhtml+xml
  application/xml
  font/opentype
  image/svg+xml
  image/x-icon
  text/css
  text/plain
  text/x-component;
# text/html is always compressed by HttpGzipModule

Thanks.

signature

Leave a Reply

Your email address will not be published. Required fields are marked *