nginx http块中需用include mime.types加载默认mime映射表,并在其后用types块自定义或覆盖类型,default_type设为application/octet-stream,通过curl验证content-type是否生效。

在 Nginx 的 http 块中配置默认的 mime.types,核心是加载并启用官方 MIME 映射表,同时确保它能被正确解析和覆盖。这不是“自定义一个 mime.types”,而是让 Nginx 正常识别 .js、.css、.png 等常见后缀对应的 Content-Type。
以下是最标准、最稳妥的做法:
✅ 正确引入默认 mime.types 文件
在 nginx.conf 的 http { ... } 块内,添加或确认存在这一行:
include mime.types;
- 这行必须写在
http块里,不能放在server或location中(否则会报错或无效)。 -
mime.types是 Nginx 安装时自带的文件,通常位于:/etc/nginx/mime.types/usr/share/nginx/mime.types- 或编译安装路径下的
conf/mime.types
- Nginx 启动时会读取该文件,构建内部哈希表,用于后续根据请求 URI 后缀(如
/style.css→css)快速匹配类型。
✅ 补充或覆盖默认类型(推荐方式)
不要直接修改原始 mime.types 文件(升级易丢失)。应在 http 块中用 types 块追加或覆盖:
http {
include mime.types;
# 自定义或修正类型(写在 include 之后,可覆盖前面同扩展名的定义)
types {
application/javascript mjs; # 支持 ES modules
font/woff2 woff2;
image/avif avif;
text/plain log;
application/wasm wasm;
}
default_type application/octet-stream;
}
- 每行左边是 MIME 类型,右边是空格分隔的一个或多个扩展名;
- 同一扩展名重复定义时,后出现的生效(所以
include mime.types应在前,自定义types在后); -
default_type是兜底项,建议设为application/octet-stream(安全下载)或text/plain(适合调试),避免浏览器误解析。
✅ 性能相关可选优化(大站点建议)
如果自定义类型很多,或遇到 type hash bucket size 报错,可调优:
http {
include mime.types;
types_hash_max_size 2048;
types_hash_bucket_size 128;
types { ... }
default_type application/octet-stream;
}
-
types_hash_max_size:增大哈希表容量,减少冲突; -
types_hash_bucket_size:调整桶大小,需是 2 的幂; - 修改后必须运行
nginx -t测试语法,再nginx -s reload生效。
✅ 验证是否生效
用 curl 检查响应头:
curl -I https://your-site.com/test.js # 应看到:Content-Type: application/javascript curl -I https://your-site.com/unknown.xyz # 应看到:Content-Type: application/octet-stream(若 default_type 已设)
不复杂但容易忽略。











