Nginx使用brotli

首先下载brotli的nginx模块
1
2
cd /opt/local/src
git clone https://github.com/google/ngx_brotli.git
接着下载brotli源代码
1
2
3
cd ngx_brotli
cd deps/brotli
git clone https://github.com/google/brotli.git
编译nginx源代码指定第三方模块
1
2
./configure 
--prefix=/opt/local/nginx --without-http_memcached_module --user=www --group=www --with-http_stub_status_module --with-openssl=/usr/ --with-pcre=/opt/local/src/pcre-8.36 --add-module=/opt/local/src/ngx_brotli
可能会报错,提示你
1
2
3
./configure: error: Brotli library is missing from the /opt/local/src/ngx_brotli/deps/brotli directory.
Please make sure that the git submodule has been checked out:
cd /opt/local/src/ngx_brotli && git submodule update --init && cd /opt/local/src/nginx-1.12.1
照着它的提示操作就好了,网络不好的话需要等很长时间,这时候就是展现技术的时候了,你懂得
1
cd /opt/local/src/ngx_brotli && git submodule update --init && cd /opt/local/src/nginx-1.12.1
操作完以后,再一次编译nginx源码
1
2
./configure 
--prefix=/opt/local/nginx --without-http_memcached_module --user=www --group=www --with-http_stub_status_module --with-openssl=/usr/ --with-pcre=/opt/local/src/pcre-8.36 --add-module=/opt/local/src/ngx_brotli
make
拷贝新的nginx bin文件
1
2
3
4
mv /opt/local/nginx/sbin/nginx /opt/local/nginx/sbin/nginx_bak
cp objs/nginx /opt/local/nginx/sbin/

/opt/local/nginx/sbin/nginx -t
不报错的话,就修改配置文件去
1
2
3
4
5
6
7
8
brotli on;
#brotli_types text/plain text/css text/xml application/xml application/json text/javascript application/javascript application/x-javascript
brotli_types *;
brotli_static off;
brotli_comp_level 11;
brotli_buffers 16 8k;
brotli_window 512k;
brotli_min_length 20;
反向代理禁用gzip
1
proxy_set_header Accept-Encoding "";
最后在Request Headers请求头和Response Headers响应头里可以看到

nginx_brotli

ngx_brotli定义了如下指令:
brotli,是否允许动态压缩响应数据,可选值为on和off,默认值为off。
1
brotli on;
brotli_types,动态压缩启用时,允许压缩的MIME types,默认值为text/html。
1
brotli_types text/plain text/css text/xml application/xml application/json text/javascript application/javascript application/x-javascript;
brotli_static,是否允许查找预处理好的、以.br结尾的压缩文件,可选值为on、off和always,默认值为off。
1
brotli_static off;
brotli_comp_level,压缩级别,可选值范围为0~11,默认值为6。
1
brotli_comp_level 11;
brotli_buffers,压缩响应数据时使用的缓冲区的数量和大小。
1
brotli_buffers 16 8k;
brotli_window,brotli使用的窗口值,默认值为512k。
1
brotli_window 512k;
brotli_min_length,响应数据的最小长度,低于该值将不使用brotli算法执行压缩操作。brotli算法使用Content-Length来确定响应数据的长度。
1
brotli_min_length 20;
★★★ 最后,brotli只对https生效