linux下为nginx添加brotli压缩需源码编译,分四步:装依赖、编译libbrotli库、编译带ngx_brotli模块的nginx、配置启用;缺一不可,否则报错unknown directive "brotli"或链接失败。

Linux 下给 Nginx 添加 Brotli 压缩,必须从源码编译,因为官方发行版(如 yum/apt)不提供带 ngx_brotli 的预编译包。整个过程分四步:装依赖、编译 libbrotli 库、编译带模块的 Nginx、配置启用。不能跳步,否则会报 unknown directive "brotli" 或链接失败。
装齐基础依赖和构建工具
不同系统命令略有差异,但目标一致:确保能编译 C 项目、链接 OpenSSL/PCRE/Zlib,并支持 Git 和 autotools。
-
CentOS/RHEL 7/8/9:
yum groupinstall "Development Tools",再执行yum install -y openssl-devel pcre-devel zlib-devel git autoconf automake libtool -
Ubuntu/Debian:
apt-get update && apt-get install -y build-essential libssl-dev libpcre3-dev zlib1g-dev git autoconf automake libtool
编译安装 libbrotli 核心库
这是关键前置步骤。Nginx 编译时需要 brotli/encode.h 头文件和 libbrotlienc.so 动态库,必须先装到系统路径(如 /usr/local),否则 configure 会失败。
- 拉取源码:
git clone https://github.com/google/brotli.git && cd brotli - 推荐用 autotools 方式(兼容性更稳):
./bootstrap && ./configure --prefix=/usr/local && make && sudo make install - 刷新动态库缓存:
sudo ldconfig(这步漏掉,Nginx 启动时会提示libbrotlienc.so: cannot open shared object file)
下载 Nginx 源码 + ngx_brotli 模块并编译
注意版本匹配:Nginx 1.24.x 对应 google/ngx_brotli 的 master 分支;若用旧版 Nginx(如 1.18),需切对应 release tag。
- 获取源码:
wget https://nginx.org/download/nginx-1.24.0.tar.gz && tar -xzf nginx-1.24.0.tar.gz - 拉取模块:
git clone https://github.com/google/ngx_brotli.git - 进入 Nginx 源码目录,运行 configure(保留你原有参数,只追加两项):
./configure \<br> --prefix=/usr/local/nginx \<br> [其他你原来用的参数,比如 --with-http_ssl_module 等] \<br> --add-dynamic-module=../ngx_brotli \<br> --with-compat
- 编译并安装:
make && sudo make install
配置启用并验证是否生效
编辑 /usr/local/nginx/conf/nginx.conf,在 http { } 块内添加:
- 加载模块(如果是动态模块方式):
load_module modules/ngx_http_brotli_filter_module.so;(放在events上方) - Brotli 配置示例:
brotli on;<br> brotli_comp_level 6;<br> brotli_min_length 20;<br> brotli_types text/plain text/css text/javascript application/javascript application/json application/xml+rss image/svg+xml font/woff2;
- 务必关闭 gzip 冲突:
gzip off;(两者同时开会导致响应头混乱) - 重启 Nginx:
sudo /usr/local/nginx/sbin/nginx -s reload - 验证:
curl -H "Accept-Encoding: br" -I https://your-domain.com/style.css,响应头中应含Content-Encoding: br











