gzip (GNU-ZIP) is a compression technology.
After gzip compression, page size can be reduced to 30% or even smaller of the original. This is why many websites use gzip compression to reduce bandwidth consumption while improving access speed, delivering a better user experience.
gzip-compressed pages require support from both the browser and the server. Essentially, the server compresses the content, and after it is transmitted to the browser, the browser decompresses and parses it.
Currently, the vast majority of browsers support parsing gzip-compressed pages.
Nginx‘s compression output is implemented through a set of gzip compression directives.
The relevant directives are placed between the http{….} curly braces.
gzip on;
// This directive enables or disables the gzip module (on/off)
gzip_min_length 1k;
// Sets the minimum byte size of a page allowed for compression. The page byte size is obtained from the content-length in the header.
The default value is 0, meaning pages are compressed regardless of size.
It is recommended to set this to a value greater than 1k, as compressing files smaller than 1k might make them larger.
gzip_buffers 4 16k;
// Sets the number and size of buffers used to store the gzip compression result data stream.
4 16k means applying for memory 4 times the unit size of 16k, based on the original data size.
gzip_http_version 1.1;
// Identifies the HTTP protocol version (1.0/1.1)
gzip_comp_level 2;
// gzip compression ratio. 1 offers the smallest compression ratio and the fastest processing speed, while 9 provides the largest compression ratio but the slowest processing speed (faster transmission but more CPU consumption).
gzip_types text/plain application/x-javascript text/css application/xml
// Matches MIME types for compression. Regardless of what is specified, the ”text/html” type will always be compressed.
gzip_vary on;
// Related to the HTTP header. Adds a Vary header, which is useful for proxy servers. Some browsers support compression, while others do not.
Therefore, to avoid wasting resources by compressing for unsupported browsers, it determines whether compression is needed based on the client’s HTTP header.
Here are two gzip compression code blocks for your reference and learning.
Nginx gzip configuration block 1:
The code is as follows:
gzip_min_length 1k;
gzip_buffers 16 64k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
Nginx gzip configuration block 2:
gzip on;
gzip_http_version 1.1;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
gzip_types text/plain text/html text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
# make sure gzip does not lose large gzipped js or css files
# see http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl
gzip_buffers 16 8k; # Disable gzip for certain browsers.
gzip_disable “MSIE