How to Implement Nginx Gzip Compression Configuration

In Nginx, you can implement file compression by configuring the gzip module, which can significantly improve transfer speed and reduce bandwidth consumption.

Steps to configure gzip compression for Nginx:

1. Ensure the gzip module is installed in Nginx

The gzip module is included by default in most Nginx distributions. You can confirm this by checking whether the http_gzip_module is present in your Nginx configuration. If you compiled Nginx from source, you need to add the --with-http_gzip_module parameter during compilation.

2. Enable gzip compression in the Nginx configuration file

Open your Nginx configuration file (usually nginx.conf or a configuration file in the sites-available directory), then add the following configuration to the http, server, or location block:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_proxied any;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";

The meaning of each configuration is as follows:

gzip on;: Enable gzip compression.
gzip_types: Specify which MIME types of response content need to be compressed.
gzip_min_length: Set the minimum response size (in bytes) for compression to be enabled.
gzip_comp_level: Set the gzip compression level. A higher level gives a greater compression ratio, but also consumes more CPU.
gzip_proxied: Set how to handle compression of responses from upstream servers when Nginx acts as a reverse proxy.
gzip_vary on;: Add "Vary: Accept-Encoding" to the response header to inform clients that the server supports gzip compression.
gzip_disable: Disable gzip compression for specific User-Agent strings.

3. Reload the Nginx configuration

After modifying the Nginx configuration file, you need to reload the configuration for changes to take effect. This can be done with the following command:

sudo nginx -s reload

Alternatively, if you are using systemd, you can run this command instead:

sudo systemctl reload nginx

4. Test that compression is working

You can use your browser's developer tools or a command-line tool (such as curl) to check the response headers for the presence of Content-Encoding: gzip, to verify that gzip compression is active.

Note: While gzip compression improves transfer efficiency, it also increases the server's CPU load. Therefore, when enabling gzip compression, you need to balance the tradeoff between transfer speed and server performance.


This is a discussion topic separated from the original thread at https://juejin.cn/post/7368665381730467855