How to Enable Gzip Compression on Nginx

In this tutorial you will learn how to enable Gzip compression on Nginx.

Enabling gzip compression is a must because it will not only make your site faster, but it will also save your server's bandwidth from getting used to serve uncompressed content, this means less bandwidth and a faster site served to your visitors.

Follow the steps below to Enable Gzip Compression

Step 1 - Open Nginx config file

Run the command below to open nginx configuration file

sudo nano /etc/nginx/nginx.conf

You can use any text editor you want, for example you can use vim editor too, to edit the config file with vim run the command

sudo vi /etc/nginx/nginx.conf

And the configuration file will be opened via the text editor that you chose, the configuration file should look like this

Step 2 - Enable Gzip compression

Once you have opened the configuration file, scroll down and find the Gzip block, and then simply uncomment all the lines that are commented, the default configuration when Gzip is not enabled should look like this.

If you can't find the Gzip block or if for some reason it doesn't exist on your configuration file, then you can simply copy paste the lines below to nginx.conf , make sure they are uncommented as shown on the image below in order to work.

#gzip on;

         #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/javascript$

After uncommenting all the lines, the configuration file should look like this

Next press CTRL +X to save the new configuration file and confirm with yes by pressing the Y button.

gzip on - Enables/Turns on Gzip compression on your server

gzip_vary on - This enables the Vary: Accept-Encoding header on the header responses, which means nginx will cache and will serve the correct content to the client.

gzip_proxied any - This means requests that are proxied will be compressed too.

gzip_comp_level 6 - Level of compression. There is a level from 1 to 9.

gzip_buffers 16 8k - This sets the compression buffers.

gzip_http_version 1.1 - Gzip will compress all requests that are in http 1.1 version.

gzip_types - The type of files that will be compressed by Nginx.

Step 3 - Restart Nginx

After enabling gzip compression on your server, now you need to restart Nginx in order for the new configuration to be activated.

Before restarting Nginx, make sure that the syntax on the configuration file nginx.conf is correct, to check whether the syntax is correct or not run the command below

sudo nginx -t 

To restart nginx simply run the following command

sudo service nginx reload

or

sudo systemctl restart nginx

Conclusion

By now you should know how to enable gzip compression on your server.

Author

Comments