Nginx的gzip_types只依据Content-Type响应头匹配MIME类型,不识别文件后缀;必须显式列出text/html、text/css、application/javascript等文本类型,禁用image/jpeg等已压缩二进制类型,并确保mime.types映射与gzip_types严格一致,最后用curl验证Content-Encoding: gzip是否生效。

Nginx 的 gzip_types 不支持扩展名压缩规则,它只依据响应头中的 Content-Type(即 MIME 类型)进行匹配,完全不识别 .js、.css、.json 等文件后缀。
也就是说:
你写 gzip_types text/css;,压缩生效的前提是该 CSS 文件响应头必须是 Content-Type: text/css;
如果它被错误地返回为 Content-Type: application/octet-stream,哪怕文件名是 style.css,也不会压缩。
真正起作用的是两件事:
-
MIME 类型是否在
gzip_types中显式列出 - 该类型是否与响应头
Content-Type完全一致(区分大小写)
常见需手动加入的 MIME 类型包括:
-
text/html(必须,漏掉则 HTML 不压缩) -
text/plain -
text/css -
text/javascript或application/javascript(推荐两者都写,兼容旧/新版浏览器) -
application/json -
application/xml、text/xml、application/xml+rss -
image/svg+xml(SVG 是文本格式,应压缩) -
text/markdown、application/typescript等新兴文本类型(需先在mime.types中映射)
⚠️ 这些类型必须逐个写出,不支持通配符:
✘ text/*、application/*、*/* —— Nginx 直接忽略,配置无效。
要让 .md、.ts、.yaml 等自定义后缀生效,必须两步走:
- 在
/etc/nginx/mime.types(Linux)或/usr/local/etc/nginx/mime.types(macOS)中补充映射:types { text/markdown md; application/typescript ts; application/yaml yaml; } - 再在
gzip_types中加入对应 MIME 类型:gzip_types ... text/markdown application/typescript application/yaml;
已压缩的二进制格式(如 image/jpeg、image/png、video/mp4、application/zip、font/woff2)不应加入,否则白耗 CPU,还可能增大体积。
验证是否真生效,不能只看配置语法正确(nginx -t),要用 curl -I 检查真实响应头是否有 Content-Encoding: gzip。


















