Nginx gzip_types按Content-Type匹配压缩,必须显式列出类型(如text/html、application/javascript等),不支持通配符,需配合gzip on等指令并实测验证。

直接在 http、server 或 location 块中写明要压缩的 MIME 类型即可。Nginx 不看文件后缀(比如 .js 或 .css),只依据响应头里的 Content-Type 字段做匹配——类型对了才压缩,不对就跳过。
必须显式列出基础文本类型
gzip_types 是覆盖式配置:一旦启用,就会完全替代 Nginx 默认仅压缩 text/html 的行为。漏掉 text/html,整个 HTML 页面就失去压缩,首屏加载明显变慢。
- 基础必选(建议直接复制):
text/html text/plain text/css text/javascript application/javascript application/json application/xml text/xml application/xml+rss image/svg+xml - 现代前端可加:
text/markdown application/typescript(需确保后端返回对应 Content-Type) - 字体类谨慎加:
application/font-woff2浏览器支持有限,且 WOFF2 本身已压缩,多数场景不推荐
绝对不要用通配符或误加二进制类型
Nginx 明确不支持 text/* 或 application/* 这类写法,配置会被直接忽略。
- 已压缩格式禁止加入:
image/jpeg image/png image/gif video/mp4 application/zip application/pdf -
application/octet-stream是“兜底类型”,常代表未识别资源(如没在 mime.types 中声明的 .log、.md),误加会导致图片、PDF 被错误压缩,务必剔除 - SVG 是例外:
image/svg+xml是纯文本 XML,必须且应当压缩
确保 MIME 类型真实生效
写了 text/markdown 没用,如果 .md 文件返回的是 application/octet-stream,Nginx 就不会压缩它——因为只比对响应头。
- 先检查
/etc/nginx/mime.types(Linux)或/usr/local/etc/nginx/mime.types(macOS) - 补充缺失映射,例如:
types {<br> text/markdown md;<br> application/typescript ts;<br>} - 再在
gzip_types中加入对应项,名称必须完全一致(区分大小写)
配合其他必要指令并实测验证
gzip_types 单独存在无效,必须和以下指令共存:
-
gzip on;—— 启用压缩功能 -
gzip_min_length 1024;—— 避免压缩过小响应(如空 JSON) -
gzip_comp_level 6;—— 平衡压缩率与 CPU 消耗(1–9,6 是常用值) -
gzip_vary on;—— 让缓存系统知道响应可能被压缩
改完配置后,用 curl 实测响应头:curl -I -H "Accept-Encoding: gzip" https://yoursite.com/main.js
确认返回头含 Content-Encoding: gzip 和 Vary: Accept-Encoding,同时核对 Content-Type 是否匹配你配置的类型(如 application/javascript)。


















