In this article, we will learn How to enable GZIP compression for NGINX on Ubuntu 18.04. Before enabling the GZIP compression lets first know more about the GZIP and compression.
What is GZIP Compression?
GZIP is a way to compress data. It is commonly used for web apps and websites. HTTP protocols have an ability to use GZIP compression. When we request a page by entering any URL in the browser, the web server compresses the data based on the request and send back it to the browser. At the browser, data will decompress and displays it to the end user. We are assuming GZIP compression is enabled at the server. Now you may ask why we need to use GZIP compression.
Why use GZIP Compression?
To understand the importance of the GZIP compression we created a sample page. It is available on our server web root directory. In this sample page, we are using the following files.
- CSS: A CSS file with size approx 4 MB
- Image: An image file with approx size 5.5 MB
- HTML Content: The HTML content for the sample page is with the size is around 4 MB.
If we load this page in a browser, the total expected size is around (4 MB + 4 MB + 4 MB + 5.5 MB = 17.5) 18 MB.
But in actual it is 13.4 MB Why? Let's check the following image.
GZIP compression is used to compress the files on the Web Server. The compressed file helps to load the web page faster and reduce the bandwidth usage.
How to enable GZIP Compression for NGINX on Ubuntu 18.04?
curl -H "Accept-Encoding: gzip" -I http://184.108.40.206/index.php curl -H "Accept-Encoding: gzip" -I http://220.127.116.11/index.html curl -H "Accept-Encoding: gzip" -I http://18.104.22.168/Test1.js curl -H "Accept-Encoding: gzip" -I http://22.214.171.124/Test1.css curl -H "Accept-Encoding: gzip" -I http://126.96.36.199/lemon.jpg
If for any of the above commands if you get an entry for "Content-Encoding: gzip" then GZIP compression is enabled for that file type.
As per the image, GZIP compression is enabled in PHP. Let’s enable it for JS, CSS, and JPG.
To Configure GZIP compression for NGINX, we need to edit the nginx.conf.
To open the nginx.conf execute the following command.
sudo nano /etc/nginx/nginx.conf
In the nginx.conf file search for the gzip settings.
As shown in the image GZIP is by default is ON. But rest of the settings are disabled. To enable the rest of the settings, we need to uncomment the required settings. In this, we need to discuss the following important lines.
It tells NGINX not to compress files smaller than 256 bytes. 256 bytes is a very small file. We hardly get any benefit from the compression. If the line is not available, then you can add it.
It tells NGINX to compress typed of files. You can add additional files. For example, we can add following types
To save the config file, press Ctrl+O and to close the nano editor press Ctrl+K.
The following image shows the after changes information.