Brotli
是Google
推出的开源压缩算法,通过变种的LZ77
算法、Huffman
编码以及二阶文本建模等方式进行数据压缩,与其他压缩算法相比,它有着更高的压缩效率,性能也比我们目前常见的Gzip
高17-25%
,可以帮我们更高效的压缩网页中的各类文件大小及脚本,从而提高加载速度,提升网页浏览体验。
1、下载Brotli
cd /www/server
#下载brotli
git clone https://github.com/google/ngx_brotli.git
cd ngx_brotli
#更新brotli
git submodule update --init
2、编译
./configure --prefix=${openresty_install_dir} --user=${run_user} --group=${run_user} --with-http_stub_status_module --with-http_v2_module --with-http_ssl_module --with-http_gzip_static_mod
ule --with-http_realip_module --with-http_flv_module --with-http_mp4_module --with-openssl=../openssl-${openssl11_ver} --with-ipv6 --add-module=/root/oneinstack/src/ngx_brotli --add-module=/
root/oneinstack/src/ngx_http_substitutions_filter_module --with-pcre=../pcre-${pcre_ver} --with-pcre-jit --with-ld-opt='-ljemalloc' ${nginx_modules_options}
[root@infvie]# nginx -V
当返回参数后面多了个 --add-module=/root/oneinstack/src/ngx_brotli 就编译成功了。
3、开启Brotli压缩
在http
段内添加以下内容来启用Brotli
压缩。
brotli on;
brotli_comp_level 6;
brotli_min_length 512;
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;
brotli_static always;
最后service nginx reload
重载配置生效即可。
Brotli
全部参数详解:
brotli on; #启用
brotli_comp_level 6; #压缩等级,默认6,最高11,太高的压缩水平可能需要更多的CPU
brotli_buffers 16 8k; #请求缓冲区的数量和大小
brotli_min_length 20; #指定压缩数据的最小长度,只有大于或等于最小长度才会对其压缩。这里指定20字节
brotli_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml text/html application/json image/svg application/font-woff application/vnd.ms-fontobject application/vnd.apple.mpegurl image/x-icon image/jpeg image/gif image/png image/bmp; #指定允许进行压缩类型
brotli_static always; #是否允许查找预处理好的、以.br结尾的压缩文件,可选值为on、off、always
brotli_window 512k; #窗口值,默认值为512k
经过实地验证,brotli和gzip可以共存。这是一个好消息,意味着Jackie可以在项目中使用启用brotli算法支持的nginx。
对于支持brotli算法的浏览器,比如Chrome 49之后的版本,使用开发者工具检查网络
Content-Encoding: br
