nginx CORS 跨域配置

配置跨域资源共享,允许前端跨域请求后端 API

语法

add_header Access-Control-Allow-Origin *;

参数

参数说明示例级别
Access-Control-Allow-Origin 允许的来源域名 add_header Access-Control-Allow-Origin https://app.example.com; 常用
Access-Control-Allow-Methods 允许的 HTTP 方法 add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE'; 常用
Access-Control-Allow-Headers 允许的请求头 add_header Access-Control-Allow-Headers 'Authorization, Content-Type'; 常用
Access-Control-Allow-Credentials 允许携带 Cookie add_header Access-Control-Allow-Credentials true; 进阶

示例

完整 CORS 配置

location /api/ {
    # 预检请求
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
        add_header Access-Control-Allow-Headers 'Authorization, Content-Type';
        add_header Access-Control-Max-Age 86400;
        return 204;
    }

    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Credentials true;
    proxy_pass http://backend;
}
处理预检请求 + 实际请求

允许所有来源(开发环境)

location /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers '*';
    proxy_pass http://localhost:3000;
}
仅限开发环境,生产环境应指定具体域名

常见错误

CORS 头在 4xx/5xx 响应中丢失 add_header 默认只在 2xx/3xx 时生效,加 always 参数:add_header ... always;

技巧

相关命令