Nginx代理字体文件和JSON接口是最稳定、无需修改前端代码的跨域方案:通过统一域名实现同源,并为字体配置CORS响应头及OPTIONS预检,为/api路径配置反向代理实现“伪同源”。

用 Nginx 代理字体文件(如 .woff2、.ttf)和 JSON 接口,是最稳定、无需修改前端代码的跨域解决方案。核心是统一域名访问,让浏览器认为资源同源。
配置静态字体文件跨域支持
字体文件被浏览器严格校验 Access-Control-Allow-Origin,尤其在 CSS 中通过 @font-face 加载时。Nginx 需显式允许跨域并支持预检(OPTIONS)。
- 在对应 server 或 location 块中添加以下响应头:
location ~* \.(woff2|woff|ttf|eot|svg)$ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
<pre class="brush:php;toolbar:false;"># 处理预检请求
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}}
- 注意:生产环境建议将
*替换为具体前端域名(如https://your-app.com),避免暴露敏感接口 - 确保字体文件 MIME 类型已正确识别(Nginx 默认支持 woff2/woff/ttf 等,若异常可补充
types { font/woff2 woff2; })
代理 JSON 接口实现“伪同源”
不改前端请求地址,只让 Nginx 把 /api/xxx 转发到后端服务,前端始终请求自己域名,彻底规避跨域。
- 示例:前端页面在
https://example.com,后端 API 在http://127.0.0.1:3000 - 在 server 块中添加反向代理规则:
location /api/ {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
<pre class="brush:php;toolbar:false;"># 可选:透传响应头(如后端未设 CORS,此处可补)
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;}
-
proxy_pass末尾的/很关键:它会剥离/api/前缀再转发,否则后端收到的是/api/users而非/users - 若后端已正确设置 CORS,Nginx 层可不加
add_header;若后端无权限控制,Nginx 补上更安全
验证与调试技巧
部署后别急着刷新页面,先用命令行或浏览器开发者工具确认行为是否符合预期。
- 检查字体请求响应头:
curl -I https://example.com/static/fonts/icon.woff2,确认含Access-Control-Allow-Origin - 检查 API 请求路径:前端应请求
/api/data,Network 面板中该请求的Domain列应显示你的主域名,而非后端地址 - 遇到 405 错误?大概率是 OPTIONS 预检未被正确处理——确认 location 块中包含
if ($request_method = 'OPTIONS')分支并返回 204 - Chrome 控制台报 “Unsafe header”?说明 JS 尝试读取了未在
Access-Control-Expose-Headers中声明的响应头(如Content-Range),按需补充即可
不推荐的替代方案提醒
有些做法看似简单,但隐患明显:
- 在后端代码里硬编码
Access-Control-Allow-Origin: *—— 无法支持带 Cookie 的请求(需同时设credentials,而*与之互斥) - 用 webpack devServer 的
proxy—— 仅限开发环境,上线即失效 - 前端改用
mode: 'no-cors'—— 请求能发出去,但拿不到响应体,JSON 数据不可用 - 禁用浏览器安全策略(如 Chrome 启动参数)—— 完全脱离真实用户环境,测试无效










