必须按租户动态启用或禁用brotli:通过map提取租户并映射压缩策略(on/gzip/off),在server中用if控制brotli/gzip开关,透传x-compression-used头,日志记录策略,敏感路径location强制关闭压缩。

不能靠全局开关统一开启 Brotli,必须按租户上下文动态启用或禁用——因为租户对压缩策略的需求不同:有的要求极致首屏速度(需开 Brotli + 高等级),有的兼容老旧客户端(需降级为 gzip 或关闭压缩),还有的敏感数据禁止任何压缩(防 CRIME 类攻击)。Nginx 本身不支持 per-tenant 压缩开关,但可通过变量+条件判断+模块组合实现逻辑隔离。
用 map 提取租户并绑定压缩开关
在 http 块中,先通过域名或 header 提取租户标识,再用 map 映射其压缩策略:
- 按子域名提取:
server_name ~^(?<tenant>[a-z0-9\-]+)\.api\.example\.com$;</tenant> - 定义压缩策略映射:
map $tenant $use_brotli {<br> default off;<br> "tenant-a" on;<br> "tenant-b" off;<br> "tenant-c" "gzip";<br>} - 注意:
"gzip"是自定义值,后续用于条件判断,不是 Nginx 内置关键字
在 server 块中按租户控制压缩行为
每个租户的 server 块内,用 if 判断并设置对应指令(Brotli 模块需已编译安装):
- 启用 Brotli:
if ($use_brotli = on) {<br> brotli on;<br> brotli_comp_level 6;<br> brotli_types application/json text/html text/css;<br>} - 禁用所有压缩(含 gzip):
if ($use_brotli = off) {<br> gzip off;<br> brotli off;<br>} - 回退到 gzip:
if ($use_brotli = gzip) {<br> brotli off;<br> gzip on;<br> gzip_comp_level 4;<br> gzip_types application/json text/html;<br>}
确保响应头与日志可追溯租户压缩状态
压缩是否生效,必须能被后端和监控系统感知:
- 透传租户与压缩信息:
add_header X-Tenant-ID $tenant;<br>add_header X-Compression-Used $use_brotli;
- 日志格式中记录实际压缩类型:
log_format tenant_log '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$tenant" "$use_brotli"';<br>access_log /var/log/nginx/tenant-a-access.log tenant_log;
- 验证方式:curl -I https://tenant-a.api.example.com/api/data,检查响应头中是否有 brotli 或 gzip,以及 X-Compression-Used 值是否匹配预期
安全兜底:禁止对敏感接口启用压缩
即使租户允许 Brotli,部分路径(如含 PII、token、JWT 的接口)必须强制禁用压缩:
- 在 location 块中覆盖租户级配置:
location ~ ^/v1/(user|auth|payment)/ {<br> gzip off;<br> brotli off;<br> add_header Vary "Accept-Encoding"; # 显式声明不压缩<br>} - 该 location 优先级高于 server 级 if 判断,确保策略不被绕过











