简介
Brotli 是一种通用的无损压缩算法,它使用 LZ77 算法的现代变体、Huffman 编码和二阶上下文建模的组合来压缩数据,其压缩比可与目前最好的通用压缩方法相媲美。它在速度上与 deflate 相似,但提供了更密集的压缩。
ngx_brotli 是两个 Nginx 模块的集合:
- ngx_brotli过滤器模块-用于即时压缩响应,
- ngx_brotli静态模块-用于提供预压缩的文件。
Brotli 与浏览器的兼容性如下图所示
安装
Nginx 的模块有两种安装方式,分别为静态编译和动态加载。
静态编译
首先使用 nginx -V
获取已安装好的编译参数,如果还没有安装,则这步忽略
下载ngx_brotli
1 2
| git clone https://github.com/google/ngx_brotli cd ngx_brotli && git submodule update --init
|
下载nginx
Nginx 版本取决于已安装的版本,如未安装可选 stable 版
1 2
| wget http://nginx.org/download/nginx-1.18.0.tar.gz tar -zxvf nginx-1.18.0.tar.gz
|
编译安装
根据第一步获取到的configure arguments
和上面软件的位置,重新整理configure arguments
,然后末尾再加上 --add-module=/path/ngx_brotli
ngx_brotli 根据实际情况进行替换,如我的下载位置为家目录下的 src 文件夹,则末尾加上--add-module=/root/src/ngx_brotli
1 2 3
| cd nginx-1.18.0 ./configure [nginx -V输出的 configure arguments ] --add-module=/path/ngx_brotli make && make install
|
动态加载
Nginx 自 1.9.11 以后版本后支持动态模块,自此,给 Nginx 添加模块再也不用重新编译 Nginx 了,通过动态模块,你可以在运行时有有选择性的加载第三方或 Nginx 官方模块。
下载ngx_brotli
1 2
| git clone https://github.com/google/ngx_brotli cd ngx_brotli && git submodule update --init
|
下载nginx
Nginx 版本取决于已安装的版本
1 2
| wget http://nginx.org/download/nginx-1.18.0.tar.gz tar -zxvf nginx-1.18.0.tar.gz
|
编译模块
1 2 3 4
| cd nginx-1.18.0/ # PS: 编译系统模块使用 --add-module, 编译第三方模块使用--add-dynamic-module。 ./configure --with-compat --add-dynamic-module=/path/ngx_brotli make modules
|
将编译好的两个文件复制到安装目录中 modules 文件夹内
1 2
| cp objs/ngx_http_brotli_filter_module.so /etc/nginx/modules/ cp objs/ngx_http_brotli_static_module.so /etc/nginx/modules/
|
模块配置
引用模块
在全局配置文件/etc/nginx/nginx.conf
中通过load_moudle
指令引用模块(根据实际情况选择配置文件进行修改)
在nginx.conf
文件的顶部添加
1 2
| load_module modules/ngx_http_brotli_filter_module.so load_module modules/ngx_http_brotli_static_module.so
|
启用模块
在全局配置文件/etc/nginx/nginx.conf
开启 Brotli。(根据实际情况选择配置文件进行修改)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| http { ... gzip on; ...
brotli on; brotli_comp_level 6; brotli_static on; brotli_types application/atom+xml application/javascript application/json application/rss+xml application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype application/x-font-ttf application/x-javascript application/xhtml+xml application/xml font/eot font/opentype font/otf font/truetype image/svg+xml image/vnd.microsoft.icon image/x-icon image/x-win-bitmap text/css text/javascript text/plain text/xml;
... }
|
修改完后使用nginx -t
命令检查配置是否正常
然后重启 Nginx 使其配置生效