Brotli 是 Google 研發(fā)的一種新興壓縮算法,可以加快網(wǎng)頁的載入速度。相較于 Gzip 壓縮率更高、性能也非常好,再基于 Chrome 的市場支配地位,Brotli 便得到迅速普及。不過要注意,它僅適用于 HTTPS。
1) 下載 Brotli 的源碼;
yum install git && cd /usr/local/src git clone https://github.com/google/ngx_brotli.git pushd ngx_brotli git submodule update --init popd
2) 執(zhí)行命令 nginx -V,configure arguments 即為現(xiàn)有的參數(shù);
nginx version: nginx/1.16.1 built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) built with OpenSSL 1.1.1c 28 May 2019 TLS SNI support enabled configure arguments: --with-http_ssl_module --with-http_v2_module --with-http_sub_module --with-openssl=../openssl-1.1.1c
3) 追加參數(shù) --add-module=../ngx_brotli,重新編譯 Nginx。本系列文中 Nginx 的源碼目錄是 /usr/local/src/nginx-1.16.1;
cd nginx-1.16.1 ./configure \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_sub_module \ --with-openssl=../openssl-1.1.1c \ --add-module=../ngx_brotli make && make install
如需執(zhí)行平滑升級 (熱部署),make 之后請不要 make install:
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old cp objs/nginx /usr/local/nginx/sbin/nginx make upgrade
4) 接著修改 nginx.conf (缺省值就夠用,篇幅所限不顯式設(shè)置。不妨再留意一下 gzip_types 和 brotli_types 指令,以允許壓縮 text/html 以外的文件,MIME 類型列表見);
http { ... gzip on; brotli on; # gzip_types text/css text/javascript application/rss+xml; # brotli_types text/css text/javascript application/rss+xml; ... }
5) 重載 Nginx,可借由 Brotli Test 等工具檢驗(yàn)效果。
nginx -t && nginx -s reload