需在 mime.types 中添加 text/plain txt 和 text/markdown md,并在 gzip_types 中显式包含 text/plain、text/markdown 等类型,确保响应头 Content-Type 与之完全匹配,Gzip 才会压缩 .txt 和 .md 文件。

要在 Nginx 中让 Gzip 正确压缩纯文本(.txt)和 Markdown(.md)文件,关键不是改后缀名,而是确保响应头里实际返回的 Content-Type 是 Nginx 能识别、且你已在 gzip_types 中明确列出的 MIME 类型——比如 text/plain 和 text/markdown。否则即使写了配置,Nginx 也不会压缩。
确认并补充 MIME 类型映射
Nginx 不会自动把 .md 文件识别为 text/markdown,必须在 mime.types 文件中显式声明:
- 打开
/etc/nginx/mime.types(Linux)或/usr/local/etc/nginx/mime.types(macOS) - 在
types { ... }块内添加两行:
text/markdown md;
注意:分号不能漏,空格要规范;text/plain 通常已存在,但 text/markdown 多数默认缺失,必须手动加。
在 gzip_types 中显式启用对应类型
gzip_types 是覆盖式配置,一旦设置就会替代默认仅压缩 text/html 的行为。务必包含基础项,并加入目标类型:
- 至少保留:
text/html text/plain text/css application/javascript application/json - 加上:
text/markdown - 示例完整写法(放在
http或server块中):
gzip_types text/html text/plain text/css application/javascript application/json text/markdown;
验证响应头是否真实匹配
配置完后,用 curl 检查实际返回的 Content-Type:
curl -I https://yoursite.com/example.md- 看响应头中是否为
Content-Type: text/markdown - 如果显示的是
application/octet-stream或text/plain,说明mime.types没生效或扩展名未正确定义,需回头检查
只有当响应头与 gzip_types 中的字符串**完全一致**(区分大小写),Gzip 才会触发压缩。
避免常见陷阱
- 不要写
text/*—— Nginx 直接忽略,无效 - 不要把
application/octet-stream加进gzip_types—— 它是兜底类型,可能误压缩图片/PDF - 确保
gzip on已开启,且和gzip_types在同一作用域(如都在http块内) - 修改后执行
nginx -t && nginx -s reload生效











