Tutorial

How To Add the gzip Module to Nginx on Ubuntu 14.04

How To Add the gzip Module to Nginx on Ubuntu 14.04
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

Introduction

How fast a website will load depends on the size of all of the files that have to be downloaded by the browser. Reducing the size of files to be transmitted can make the website not only load faster, but also cheaper to those who have to pay for their bandwidth usage.

gzip is a popular data compression program. You can configure Nginx to use gzip to compress files it serves on the fly. Those files are then decompressed by the browsers that support it upon retrieval with no loss whatsoever, but with the benefit of smaller amount of data being transferred between the web server and browser.

Because of the way compression works in general, but also how gzip works, certain files compress better than others. For example, text files compress very well, often ending up over two times smaller in result. On the other hand, images such as JPEG or PNG files are already compressed by their nature and second compression using gzip yields little or no results. Compressing files use up server resources, so it is best to compress only those files that will reduce its size considerably in result.

In this guide, we’ll discuss how to configure Nginx installed on your Ubuntu 14.04 server to utilize gzip compression to reduce the size of content sent to website visitors.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Creating Test Files

In this step, we will create several test files in the default Nginx directory to text gzip’s compression.

To make a decision what kind of file is served over the network, Nginx does not analyze the file contents because it wouldn’t be fast enough. Instead, it just looks up the file extension to determine its MIME type, which denotes the purpose of the file.

Because of this behavior, the contents of the test files is irrelevant. By naming the files appropriately, we can trick Nginx into thinking that one entirely empty file is an image and the another, for example, is a stylesheet.

In our configuration, Nginx will not compress very small files, so we’re are going to create test files that are exactly 1 kilobyte in size. This will allow us to verify whether Nginx uses compression where it should, compressing one type of files and not doing so with the others.

Create a 1 kilobyte file named test.html in the default Nginx directory using truncate. The extension denotes that it’s an HTML page.

  1. sudo truncate -s 1k /usr/share/nginx/html/test.html

Let’s create a few more test files in the same manner: one jpg image file, one css stylesheet, and one js JavaScript file.

  1. sudo truncate -s 1k /usr/share/nginx/html/test.jpg
  2. sudo truncate -s 1k /usr/share/nginx/html/test.css
  3. sudo truncate -s 1k /usr/share/nginx/html/test.js

Step 2 — Checking the Default Behavior

The next step is to check how Nginx behaves in respect to compression on a fresh installation with the files we have just created.

Let’s check if HTML file named test.html is served with compression. The command requests a file from our Nginx server, and specifies that it is fine to serve gzip compressed content by using an HTTP header (Accept-Encoding: gzip).

  1. curl -H "Accept-Encoding: gzip" -I http://localhost/test.html

In response, you should see several HTTP response headers:

Nginx response headers
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Tue, 19 Jan 2016 20:04:12 GMT
Content-Type: text/html
Last-Modified: Tue, 04 Mar 2014 11:46:45 GMT
Connection: keep-alive
Content-Encoding: gzip

In the last line, you can see the Content-Encoding: gzip header. This tells us that gzip compression has been used to send this file. This happened because on Ubuntu 14.04, Nginx has gzip compression enabled automatically after installation with its default settings.

However, by default, Nginx compresses only HTML files. Every other file on a fresh installation will be served uncompressed. To verify that, you can request our test image named test.jpg in the same way.

  1. curl -H "Accept-Encoding: gzip" -I http://localhost/test.jpg

The result should be slightly different than before:

Nginx response headers
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Tue, 19 Jan 2016 20:10:34 GMT
Content-Type: image/jpeg
Content-Length: 0
Last-Modified: Tue, 19 Jan 2016 20:06:22 GMT
Connection: keep-alive
ETag: "569e973e-0"
Accept-Ranges: bytes

There is no Content-Encoding: gzip header in the output, which means the file was served without compression.

You can repeat the test with test CSS stylesheet.

  1. curl -H "Accept-Encoding: gzip" -I http://localhost/test.css

Once again, there is no mention of compression in the output.

Nginx response headers for CSS file
HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Tue, 19 Jan 2016 20:20:33 GMT
Content-Type: text/css
Content-Length: 0
Last-Modified: Tue, 19 Jan 2016 20:20:33 GMT
Connection: keep-alive
ETag: "569e9a91-0"
Accept-Ranges: bytes

Step 3 — Configuring Nginx’s gzip Settings

The next step is to configure Nginx to not only serve compressed HTML files, but also other file formats that can benefit from compression.

To change the Nginx gzip configuration, open the main Nginx configuration file in nano or your favorite text editor.

  1. sudo nano /etc/nginx/nginx.conf

Find the gzip settings section, which looks like this:

/etc/nginx/nginx.conf
. . .
##
# `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 by default, gzip compression is enabled by the gzip on directive, but several additional settings are commented out with # comment sign. 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. This is very small files barely benefit from compression.
  • Append the gzip_types directive with additional file types denoting web fonts, ico icons, and SVG images.

After these changes have been applied, the settings section should look like this:

/etc/nginx/nginx.conf
. . .
##
# `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_min_length 256;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;
. . .

Save and close the file to exit.

To enable the new configuration, restart Nginx.

  1. sudo service nginx restart

Step 4 — Verifying the New Configuration

The next step is to check whether changes to the configuration have worked as expected.

We can test this just like we did in step 2, by using curl on each of the test files and examining the output for the Content-Encoding: gzip header.

  1. curl -H "Accept-Encoding: gzip" -I http://localhost/test.html
  2. curl -H "Accept-Encoding: gzip" -I http://localhost/test.jpg
  3. curl -H "Accept-Encoding: gzip" -I http://localhost/test.css
  4. curl -H "Accept-Encoding: gzip" -I http://localhost/test.js

Now only test.jpg, which is an image file, should stay uncompressed. In all other examples, you should be able to find Content-Encoding: gzip header in the output.

If that is the case, you have configured gzip compression in Nginx successfully!

Conclusion

Changing Nginx configuration to fully use gzip compression is easy, but the benefits can be immense. Not only visitors with limited bandwidth will receive the site faster but also Google will be happy about the site loading faster. Speed is gaining traction as an important part of modern web and using gzip is one big step to improve it.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar

Software Engineer, CTO @Makimo

Creating bespoke software ◦ CTO & co-founder at Makimo. I’m a software enginner & a geek. I like making impossible things possible. And I need tea.


Default avatar

staff technical writer

hi! i write do.co/docs now, but i used to be the senior tech editor publishing tutorials here in the community.


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

javascript files weren’t being gzipped for me until I also added

application/javascript

Thank you so much for the detailed explanation. Till now I have read two articles of DO and, to be honest, explanations were easily understandable.

So, thank you so much again!

Is there a way to serve compressed files made during build time rather than on the fly as there would be a performance impact each time the files are compressed per request and also per user.

Getting this error when I try to update the config file:

“Job for nginx.service failed because the control process exited with error code. See “systemctl status nginx.service” and “journalctl -xe” for details.”

Had this on another DigitalOcean server whith nginx and Laravel installed. Any ideas?

ttthank’s man <3 realy thank’s lot

How can we add the gzip compression of svg files?

I’ve got a problem on Step 2: Failed to connect to localhost port 80: Connection refused Any solution about that? I’ve searched out here in the forum and found lot of similar issues, but not sure about which one I could try. Thanks in advance

Isn’t image/jpeg also missing from the example? .jpgs weren’t gzipped until I added that to the list of gzip_types.

i would really like to have some idea about HPACK as well. thanks in advance Muğla Emlak

Nice tutorial! :) Just one question: Is it superfluous to enable this if I have a Wordpress site on my droplet that already has gzip compression via plugins like W3TC?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.