nginx 正确交付 web 字体需为 .woff2、.woff、.ttf、.eot、.otf 等后缀显式映射标准 mime 类型,如 font/woff2、font/woff 等,并通过 http 块内联 types 或独立配置文件引入,同时设置 default_type 为 application/octet-stream 以兜底。

要让 Nginx 正确交付 Web 字体(如 .woff2、.woff、.ttf、.eot、.otf),关键不是“启用字体支持”,而是确保每个后缀都映射到浏览器认可的标准 MIME 类型。配错会导致字体加载失败、控制台报 MIME type mismatch 或 CORS 阻断。
必须声明的字体 MIME 类型与对应后缀
Nginx 默认 mime.types 对部分字体支持不全(尤其 .woff2 在旧版本中常缺失),需显式补充:
-
.woff2→font/woff2(不是application/font-woff2,后者兼容性差) -
.woff→font/woff(推荐,比application/font-woff更通用) -
.ttf→font/ttf(或application/x-font-ttf,但font/ttf是 IANA 注册标准) -
.eot→application/vnd.ms-fontobject(IE 专用,不可省略) -
.otf→font/otf -
.svg(仅当用作字体时)→image/svg+xml(注意:SVG 字体已基本弃用,但仍有遗留)
在 Nginx 中安全添加字体类型映射
不要直接修改 /etc/nginx/mime.types(升级可能覆盖,协作易冲突)。推荐以下任一方式:
-
✅ 方式一:在
http块中内联types(简洁、易维护)http { include mime.types; types { font/woff2 woff2; font/woff woff; font/ttf ttf; font/otf otf; application/vnd.ms-fontobject eot; image/svg+xml svg; } default_type application/octet-stream; } -
✅ 方式二:分离配置文件(更清晰,推荐用于多站点环境)
创建/etc/nginx/conf.d/font.mime:types { font/woff2 woff2; font/woff woff; font/ttf ttf; font/otf otf; application/vnd.ms-fontobject eot; image/svg+xml svg; }然后在
http块中引入(位置应在include mime.types;之后):include mime.types; include /etc/nginx/conf.d/font.mime; default_type application/octet-stream;
务必设置 default_type
未匹配后缀(如 .asset、.br 或临时文件)若无兜底类型,Nginx 不返回 Content-Type 头,浏览器行为不可控。设为 application/octet-stream 可强制下载,避免误解析。
验证是否生效
执行 nginx -t && nginx -s reload 后,用 curl 检查响应头:
curl -I https://yoursite.com/fonts/icon.woff2
应看到:Content-Type: font/woff2
若返回 text/plain 或 text/html,说明未匹配成功,优先排查拼写(如 woff2 写成 wof2)、include 路径是否正确、或作用域是否被嵌套 location 隔离。
不复杂但容易忽略。











