在 Nginx 的 location 块中配置 CORS 头可实现路径级精准控制,如仅 /api/ 支持跨域;需设置 Access-Control-Allow-Origin(非 *)、Methods、Headers 等头,并用 if 拦截 OPTIONS 预检返回 204;带 credentials 时须指定具体源并添加 Access-Control-Allow-Credentials true。

在 Nginx 的 location 块中添加 CORS 头,是解决前端跨域请求最常用且安全的方式。关键在于:只对需要跨域的路径精准设置响应头,避免全局开放带来安全隐患。
为什么要在 location 段配置而不在 server 段?
将 CORS 头放在 location 块中,可以做到路径级控制。比如只允许 /api/ 接口支持跨域,而静态资源(/static/、/images/)不带 Access-Control-Allow-Origin,防止敏感接口被意外暴露。
基础 CORS 头的标准写法
以下是最小可用配置,适用于简单 GET/POST 请求(无 Cookie、无自定义 Header):
注意:origin 值不应写死为 *(除非明确不需要携带凭证);若需支持 withCredentials,必须指定具体域名且不能用通配符。
add_header Access-Control-Allow-Origin "https://your-frontend.com";add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";add_header Access-Control-Expose-Headers "Content-Length,Content-Range";
必须处理 OPTIONS 预检请求
浏览器对复杂请求(如带 Authorization 或 Content-Type: application/json)会先发一个 OPTIONS 请求。Nginx 需拦截并直接返回 204,不转发给后端:
- 在对应
location内添加:if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin "https://your-frontend.com"; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS"; add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization"; add_header Access-Control-Max-Age 1728000; add_header Content-Type 'text/plain; charset=utf-8'; add_header Content-Length 0; return 204; } - 确保该
if块在proxy_pass或fastcgi_pass之前,否则预检请求仍会被转发
带凭证(Cookie / Authorization)时的注意事项
若前端设置了 credentials: 'include',后端必须满足三项:
-
Access-Control-Allow-Origin不能为*,必须是确切源(如https://app.example.com) - 必须显式开启:
add_header Access-Control-Allow-Credentials "true"; - 预检响应中也要包含该头(即
if ($request_method = 'OPTIONS')块里同样加这行)

















