Nginx仅根据请求路径末尾扩展名(如.js、.woff2)查types块映射MIME类型,决定Content-Type响应头;配错会导致样式失效、脚本被拒等,应避免直接修改默认mime.types,推荐在http/server块中内联types或include自定义文件,并配置default_type兜底,修改后需nginx -t校验并reload生效。

Nginx 识别静态资源类型,只看请求路径末尾的扩展名(比如 .js、.woff2),不读文件内容。它靠 types 块做后缀到 MIME 类型的映射,匹配结果直接决定响应头里的 Content-Type。配错会导致浏览器下错文件、样式不生效、字体加载失败、ES 模块报错等。
用 types 块补充或覆盖默认映射
别直接改 /etc/nginx/mime.types——升级可能被覆盖,多人协作易混淆。推荐在 http 或 server 块里用内联 types 块,或 include 自定义文件:
- 内联写法(简洁,适合少量新增):
types {<br> application/javascript js mjs;<br> font/woff2 woff2;<br> image/avif avif;<br> application/wasm wasm;<br>} - 分离写法(更清晰,推荐):
在/etc/nginx/conf.d/custom.mime中写:types {<br> application/json json json5;<br> application/font-woff2 woff2;<br> image/webp webp;<br>}
再在主配置中加:include /etc/nginx/conf.d/custom.mime;
确保未命中时有合理兜底
如果请求的后缀(如 .tsbuildinfo 或新出的 .vitepress)在所有 types 块里都没定义,Nginx 默认不设 Content-Type 头(除非你配置了 default_type)。
- 不设
default_type:响应头无Content-Type→ 浏览器按text/plain或application/octet-stream处理,现代前端资源大概率被拒绝 - 建议显式配置:
default_type application/octet-stream;(安全兜底)或default_type text/plain;(调试友好) - 注意作用域:
default_type放在http块最稳妥,避免location内遗漏导致继承失效
验证和排查常见问题
配完必须 nginx -t && nginx -s reload,否则不生效。检查是否生效,最直接的方式是 curl 查响应头:
-
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,需确认该location所在作用域是否包含或可访问到types块
常用现代格式参考映射
以下这些格式容易被默认 mime.types 忽略,建议显式加入:
-
application/javascript→js mjs cjs -
application/json→json json5 -
font/woff2→woff2 -
image/avif→avif -
image/webp→webp -
application/wasm→wasm -
application/octet-stream→bin dat(二进制数据)


















