为Nginx启用Brotli压缩算法
in web with 3 comments

什么是Brotli

项目地址:https://github.com/google/ngx_brotli

Brotli最初发布于2015年,用于网络字体的离线压缩。Google软件工程师在2015年9月发布了包含通用无损数据压缩的Brotli增强版本,特别侧重于HTTP压缩。其中的编码器被部分改写以提高压缩比,编码器和解码器都提高了速度,流式API已被改进,增加更多压缩质量级别。新版本还展现了跨平台的性能改进,以及减少解码所需的内存。

与常见的通用压缩算法不同,Brotli使用一个预定义的120千字节字典。该字典包含超过13000个常用单词、短语和其他子字符串,这些来自一个文本和HTML文档的大型语料库。预定义的算法可以提升较小文件的压缩密度。

使用brotli取代deflate来对文本文件压缩通常可以增加20%的压缩密度,而压缩与解压缩速度则大致不变。

浏览器支持情况

安装配置

我用的环境是Ubuntu + lnmp.org一键脚本 只需要重新编译一遍nginx就好

下载Brotli源码

最新版已经无需安装额外依赖 bagder/libbrotli

cd /usr/local/src/
git clone https://github.com/google/ngx_brotli.git
cd ngx_brotli
git submodule update --init

下载Nginx的源码

我使用的是nginx/1.12.2

cd /usr/local/src
VERSION=1.12.2 #换成你想要的版本
wget http://nginx.org/download/nginx-${VERSION}.tar.gz
tar -xvzf nginx-${VERSION}.tar.gz

获取Nginx原来的编译选项

root@HAN:# nginx -V
nginx version: nginx/1.12.2
built by gcc 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.6) 
built with OpenSSL 1.0.2n  7 Dec 2017
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_sub_module --with-ld-opt=-ljemalloc  --with-openssl=../openssl 

configure arguments: 后面就是你原先的编译选项

编译Nginx

cd /usr/local/src/nginx-${VERSION}
./configure {添加上原先的编译选项} --add-module=/usr/local/src/ngx_brotli
# 例如: ./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-http_sub_module --with-ld-opt=-ljemalloc  --with-openssl=../openssl --add-module=/usr/local/src/ngx_brotli
make && make install

检查是否安装正常

nginx -V
nginx -t

修改Nginx配置文件

找到Nginx的全局配置文件,我的在/usr/local/nginx/conf/nginx.conf

在 http 段加入一下代码

brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;

重启Nginx

/etc/init.d/nginx restart

打开Chrome开发者模式 Network,刷新网页,看到Content-Encoding: br响应头表示成功

Responses
  1. 看了你的文章,觉得很不错!希望与您互相友情链接?

    站点名:建站知道网

    站点描述:新老站长都喜欢的技术性优秀网站!。

    站点链接:wozhidaole.com.cn

    申请交换友情链接!如果同意的话请回复一下

    Reply
  2. 虽然半个字都看不懂,不过还是欢迎失踪人口回归

    Reply
    1. @HunTrue

      不容易啊,将近半年更新一篇文章。

      Reply