Skip to content

nginx brotli 配置

nginx brotli 官方文档上介绍

nginx brotli github 开源仓库 https://github.com/google/ngx_brotli nginx 动态模块 https://docs.nginx.com/nginx/admin-guide/dynamic-modules/dynamic-modules/

nginx 官方文档 https://docs.nginx.com/nginx/admin-guide/dynamic-modules/brotli/

什么是 brotli

Brotli is a generic-purpose lossless compression algorithm that compresses data using a combination of a modern variant of the LZ77 algorithm, Huffman coding and 2nd order context modeling, with a compression ratio comparable to the best currently available general-purpose compression methods. It is similar in speed with deflate but offers more dense compression.

ngx_brotli is a set of two nginx modules:

ngx_brotli filter module - used to compress responses on-the-fly,
ngx_brotli static module - used to serve pre-compressed files.

中文翻译:

Brotli 是一种通用的无损压缩算法,它结合使用了现代化的 LZ77 算法变体、霍夫曼编码和二阶上下文建模来压缩数据,其压缩比与当前可用的最佳通用压缩方法相当。它的速度与 deflate 相当,但提供了更密集的压缩效果。

ngx_brotli 是两个 nginx 模块的集合:

ngx_brotli filter 模块 - 用于即时压缩响应,
ngx_brotli static 模块 - 用于提供预压缩的文件。

使用开源镜像包含 brotli

自己手动编译包含 brotli

看这个文章 15-nginx-动态模块 如何给-docker-nginx-官方镜像添加-brotli-动态模块

发布自己的 brotli 镜像

把自己编译的 brotli 镜像发布到 docker hub https://github.com/xieerduos/nginx-brotli

拉取镜像

bash
docker pull lishaohai/nginx-brotli:1.25.4

github 代码仓库

https://github.com/xieerduos/nginx-brotli

运行容器

bash
docker run --name mynginx -d -p 8888:80 lishaohai/nginx-brotli:1.25.4

使用 curl 测试

使用 curl windows 测试,如果 Content-Encoding 头包含 br,这表明响应确实使用了 Brotli 压缩。如果这个头不存在,或者它显示的是 gzip 或其他值,那么服务器可能不支持 Brotli 压缩,或者请求的资源没有被压缩。

发送带有 Brotli 压缩请求的命令:

bash
curl -I -H "Accept-Encoding: br" http://localhost:8888

Windows 日志如下:

powershell
PS C:\Users\Administrator\Desktop\nginx-course\curl-8.7.1_7-win64-mingw\bin> .\curl.exe --version
curl 8.7.1 (x86_64-w64-mingw32) libcurl/8.7.1 LibreSSL/3.9.1 zlib/1.3.1 brotli/1.1.0 zstd/1.5.6 WinIDN libpsl/0.21.5 libssh2/1.11.0 nghttp2/1.61.0 ngtcp2/1.4.0 nghttp3/1.2.0
Release-Date: 2024-03-27
Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns ldap ldaps mqtt pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp ws wss
Features: alt-svc AsynchDNS brotli HSTS HTTP2 HTTP3 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM PSL SPNEGO SSL SSPI threadsafe UnixSockets zstd
powershell
PS C:\Users\Administrator\Desktop\nginx-course\curl-8.7.1_7-win64-mingw\bin>  .\curl.exe -I -H "Accept-Encoding: br" http://localhost:8888
HTTP/1.1 200 OK
Server: nginx/1.25.4
Date: Tue, 30 Apr 2024 16:31:55 GMT
Content-Type: text/html
Last-Modified: Wed, 14 Feb 2024 16:03:00 GMT
Connection: keep-alive
ETag: W/"65cce434-267"
Content-Encoding: br

PS C:\Users\Administrator\Desktop\nginx-course\curl-8.7.1_7-win64-mingw\bin>