Publish: 2019-03-21 | Modify: 2019-03-21
Google believes that the time of Internet users is valuable, and their time should not be wasted on long web page loading times. Therefore, in September 2015, Google introduced the lossless compression algorithm Brotli. Brotli uses a variant of the LZ77 algorithm, Huffman coding, and second-order text modeling to compress data, and it has higher compression efficiency compared to other compression algorithms.
Nginx does not support the ngx_brotli module by default, so it needs to be compiled separately. Here is the compilation method:
# Download Brotli first
git clone https://github.com/google/ngx_brotli.git
# Enter the directory
cd ngx_brotli
# Update Brotli
git submodule update --init
# Go to the Nginx source code directory
cd xxx/nginx
# Generate the makefile (add the module based on your own usage)
./configure ... --add-module=../ngx_brotli
# Compile Nginx
make && make install
If there are no compilation errors, you can see the ngx_brotli module by entering nginx -V
, as shown in the screenshot below.
To enable Brotli compression, modify nginx.conf
and add the following content within the http
section:
# Enable Brotli compression
brotli on;
# Compression level, ranging from 0 to 11. The default value is 6. Setting it too high may consume additional server CPU.
brotli_comp_level 6;
# Set the minimum response size in bytes for compression
brotli_min_length 512;
# Specify which MIME types to compress
brotli_types text/plain text/javascript text/css text/xml text/x-component application/javascript application/x-javascript application/xml application/json application/xhtml+xml application/rss+xml application/atom+xml application/x-font-ttf application/vnd.ms-fontobject image/svg+xml image/x-icon font/opentype;
# Whether to allow looking up precompressed .br files. Possible values are on, off, and always.
brotli_static always;
Finally, don't forget to reload Nginx to make it effective: nginx -s restart
.
The content encoding type used by browsers that support Brotli compression algorithm is br. For example, the Accept-Encoding value in the request header of Chrome browser (only when using HTTPS) is as follows:
Accept-Encoding: gzip, deflate, sdch, br
If the server supports Brotli algorithm, it will return the following response header:
Content-Encoding: br
Brotli and Gzip can coexist, so it is recommended to enable both compressions. In the case where some older browsers do not support Brotli, it will automatically degrade to Gzip for processing.
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.