Gzip compression in Nginx is a method of compressing HTTP responses sent from the Nginx web server to the client’s web browser. With GZIP enabled , Nginx will try to compress the content before sending it to clients. The client’s browser then decompresses the received data to its original form before rendering it.
By efficiently minimizing data transfer over the network, this leads to faster page load times and decreased bandwidth usage.
To enable Gzip compression in Nginx, follow these steps:
Step 1: Create a Gzip configuration file
- Go to the location /etc/nginx/conf.d and create a file named gzip.conf:
vim /etc/nginx/conf.d/gzip.conf
Add the following lines to the gzip.conf file and save it:
gzip on; gzip_vary on; gzip_comp_level 6; gzip_min_length 1024; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml; gzip_disable "MSIE [1-6]\.";
- gzip on; – enables gzip compression
- gzip_vary on: – tells proxies to cache both gzipped and regular versions of a resource
- gzip_comp_level – specifies the compression level (6 is a commonly used value).
- gzip_min_length 1024; – informs NGINX not to compress anything smaller than the defined size
- gzip_proxied – compress data even for clients that are connecting via proxies (here we’re enabling compression if: a response header includes the “expired”, “no-cache”, “no-store”, “private”, and “Authorization” parameters)
- gzip_types – enables the types of files that can be compressed
- gzip_disable “MSIE [1-6]\.”; – disable compression for Internet Explorer versions 1-6
Step 2: Include the Gzip configuration file
- Open the Nginx configuration file (/etc/nginx/nginx.conf) with a text editor:
vim /etc/nginx/nginx.conf
- Ensure that the following line is present.
include /etc/nginx/conf.d/*.conf;
Step 3: Test the Nginx configuration
- Check the validity of the Nginx configuration to ensure there are no syntax errors:
nginx -t
Step 4: Reload Nginx
- If the configuration test is successful, reload Nginx to apply the changes:
service nginx reload
After following these steps, Nginx should now compress the specified file types and send them to clients with gzip support. This can significantly reduce the size of the transferred data and improve the overall performance of your website.