Nginx 通过 types 指令映射文件扩展名与 MIME 类型,依赖后缀而非内容,决定 Content-Type 响应头;需在 http 块中 include mime.types,并可安全自定义补充类型及设置 default_type 防无类型响应。

Nginx 通过 types 指令建立文件扩展名与 MIME 类型的映射关系,只看请求路径末尾的后缀(如 .js、.woff2),不读文件内容;映射结果直接决定响应头中的 Content-Type。配错会导致浏览器拒绝执行脚本、样式不生效、字体加载失败等。
正确引入默认 mime.types 文件
在 nginx.conf 的 http { } 块中,必须包含这一行:
include mime.types;
该语句不能放在 server 或 location 块内,否则无效。文件通常位于 /etc/nginx/mime.types 或 /usr/share/nginx/mime.types,由 Nginx 安装时自带,提供常见格式(.html、.css、.png 等)的基础映射。
安全补充或覆盖类型(不改原始文件)
避免直接编辑 mime.types——升级可能被覆盖,协作易出错。推荐以下任一方式:
-
内联 types 块(适合少量新增):
types { application/javascript js mjs; font/woff2 woff2; image/avif avif; application/wasm wasm; } -
分离配置 + include(更清晰,推荐):
新建/etc/nginx/conf.d/custom.mime,写入自定义映射;
在http块中添加include /etc/nginx/conf.d/custom.mime;
注意:自定义 types 块应放在 include mime.types; 之后,才能覆盖默认值;若需确保关键类型(如 .mjs)命中 application/javascript,建议显式声明,不要依赖旧版 text/javascript。
设置 default_type 防止无类型响应
当请求后缀(如 .vitepress、.tsbuildinfo)未在任何 types 块中定义时,Nginx 默认不发送 Content-Type 头,浏览器可能按 text/plain 或 application/octet-stream 处理,导致现代资源被拒绝。
- 推荐在
http块中设为:default_type application/octet-stream;(安全兜底)
或default_type text/plain;(调试友好) - 放在
http块最稳妥,避免location内遗漏导致继承失效
验证配置是否生效
修改后必须执行两步:
-
nginx -t检查语法和路径是否正确 -
nginx -s reload重载配置(不中断服务)
用 curl -I 实测响应头:
-
curl -I https://yoursite.com/app.js→ 应返回Content-Type: application/javascript -
curl -I https://yoursite.com/icon.avif→ 应返回Content-Type: image/avif
若返回 text/html 或 text/plain,说明未匹配上,优先排查:
– types 块是否漏写或拼写错误(如 wof2 少一个 f)
– include 路径是否正确、文件是否存在可读
– 正则 location ~* \.(js|css)$ 是否所在作用域能访问到 types 块


















