Logo
Loading...
Published on

Enabling gzip encoding in NGINX

Author

So after deployment of my blog website I've decided to test it with Lighthouse in Chrome and found out I'm missing gzip encoding.

How gzip encoding works:

  • Browser(Client) sending request with Accept-Encoding: gzip header, which specifies that it is fine to serve gzip compressed content
  • NGINX should see this header gzip content and return Content-Encoding: gzip header in response

So let's go to NGINX settings and see what's going on there:

cat /etc/nginx/nginx.conf 

And we should see block with gzip settings

##
# `gzip` Settings
#
#
gzip on;
gzip_disable "msie6";

# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

You can see that gzip compression is indeed enabled by the gzip on directive, but several additional settings are commented out with # sign and have no effect. We’ll make several changes to this section: - Enable the additional settings by uncommenting all of the commented lines (i.e., by deleting the # at the beginning of the line)

  • Add the gzip_min_length 256; directive, which tells Nginx not to compress files smaller than 256 bytes. Very small files barely benefit from compression.
  • Append the gzip_types directive with additional file types denoting web fonts, icons, XML feeds, JSON structured data, and SVG images.
##
# Gzip Settings
##

gzip on;

gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types
  application/atom+xml
  application/geo+json
  application/javascript
  application/x-javascript
  application/json
  application/ld+json
  application/manifest+json
  application/rdf+xml
  application/rss+xml
  application/xhtml+xml
  application/xml
  font/eot
  font/otf
  font/ttf
  image/svg+xml
  text/css
  text/javascript
  text/plain
  text/xml;
....

Restart nginx:

sudo systemctl restart nginx

Now when we check our website with appropriate content type we should see Content-Encoding: gzip header in response.