---

title: CORS 预检缓存:Access-Control-Max-Age 的取舍与风险

keywords:

  • CORS
  • Preflight
  • Access-Control-Max-Age
  • OPTIONS
  • 安全边界

description: 说明 CORS 预检的缓存机制与 Access-Control-Max-Age 的影响,如何在性能与安全之间取得平衡,并给出服务器示例与兼容建议。

categories:

  • 应用软件
  • 办公软件

---

概述

预检(OPTIONS)用于验证跨源请求方法与头部。Access-Control-Max-Age 决定预检结果的缓存时长,可降低频繁预检开销,但不宜设置过长以免放大误配风险。

示例:Nginx/Node 配置

location /api/ {
  if ($request_method = OPTIONS) {
    add_header Access-Control-Allow-Origin "https://app.example";
    add_header Access-Control-Allow-Methods "GET, POST, PUT";
    add_header Access-Control-Allow-Headers "Content-Type, Authorization";
    add_header Access-Control-Max-Age 600;
    return 204;
  }
  add_header Access-Control-Allow-Origin "https://app.example";
  proxy_pass http://backend;
}
// Express 中处理预检
app.options('/api/*', (req, res) => {
  res.set({
    'Access-Control-Allow-Origin': 'https://app.example',
    'Access-Control-Allow-Methods': 'GET,POST,PUT',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    'Access-Control-Max-Age': '600'
  })
  res.sendStatus(204)
})

工程建议

  • 精准白名单:仅允许必要来源/方法/头;动态场景以令牌或签名鉴权为主。
  • 缓存时长:根据风险与变更频率设置中等 TTL(如 10–30 分钟);重大变更前缩短 TTL。
  • 监控与告警:记录跨源失败与预检命中;避免误配置长期生效。

参考与验证

  • MDN CORS 预检说明:https://developer.mozilla.org/docs/Web/HTTP/CORS#preflighted_requests
  • WHATWG Fetch 规范:https://fetch.spec.whatwg.org/
  • web.dev CORS 与安全实践:https://web.dev/articles/cors

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部