关键是要准确映射常见前端资源后缀到正确 MIME 类型,需显式 include mime.types 和自定义 custom.mime(含 woff2、avif 等),location 中须显式声明 types 或 include,且 default_type 不可省略,最后用 curl -I 验证响应头。

关键不是“配全所有类型”,而是让每个常见前端资源后缀都准确映射到浏览器能执行或渲染的 MIME 类型,同时避免默认 fallback 导致 Content-Type: application/octet-stream 或 text/plain 这类错误响应头。
必须启用并合理组织 types 映射
Nginx 不会自动加载 mime.types,你得在 http 块里显式写上:
-
include mime.types;—— 加载系统默认映射(含.css → text/css、.js → application/javascript等基础项) - 但旧版
mime.types缺失现代格式,所以要额外补全:比如.woff2、.avif、.webp、.mjs、.json5、.wasm - 推荐新建
/etc/nginx/conf.d/custom.mime,内容如:
types {
application/javascript js mjs;
font/woff2 woff2;
image/avif avif;
image/webp webp;
application/wasm wasm;
application/json json json5;
}再在 http 块中 include /etc/nginx/conf.d/custom.mime;。注意顺序:放在 include mime.types; 之后,可覆盖默认行为;放在之前,则可能被覆盖。
location 块里别丢掉 types 继承
正则匹配的 location(例如 location ~* \.(js|css|png)$)不会自动继承外层 types,容易导致 MIME 错误:
- ❌ 错误写法:
location ~* \.js$ { root /var/www; }—— 没声明 types,也没 include,最终靠default_type回退 - ✅ 正确做法一:在该 location 内直接加内联 types:
types { application/javascript js; } - ✅ 正确做法二:复用已有配置:
include /etc/nginx/conf.d/custom.mime;
default_type 是安全底线,不能省
没匹配到任何后缀时,Nginx 默认不发 Content-Type 头,浏览器会按 text/plain 或 application/octet-stream 处理,JS 不执行、字体不加载、JSON 被下载。
- 务必在
http块顶部或中部设置:default_type application/octet-stream; - 开发调试阶段可用
default_type text/plain;,便于快速发现未映射后缀 - 不要放在
server或location里——作用域太小,容易遗漏
改完必须验证,不能只信 nginx -t
配置语法正确 ≠ 实际生效。用 curl -I 直接看响应头最可靠:
-
curl -I https://yoursite.com/app.mjs→ 应返回Content-Type: application/javascript -
curl -I https://yoursite.com/logo.avif→ 应返回Content-Type: image/avif - 如果返回
text/html或text/plain,说明 types 没命中:检查拼写(woff2不是wof2)、路径是否 include 成功、重复定义是否意外覆盖


















