location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/api/;
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' $http_origin;
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';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}
proxy_pass http://127.0.0.1:8080/api/;
这一行的功能是将接收到的请求转发到另一个服务器上。
-
添加 CORS 相关的头部信息:
add_header 'Access-Control-Allow-Origin' $http_origin;
:这行指定哪些域可以访问资源。这里使用$http_origin
变量动态地将Origin
请求头中的值用作响应头中的值,这样请求来自哪个源,响应就允许哪个源。add_header 'Access-Control-Allow-Credentials' 'true';
:允许前端请求携带证书(如 Cookies 和 HTTP 认证相关数据)。add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
:声明服务器支持的请求方法。add_header 'Access-Control-Allow-Headers' '*';
:允许所有自定义的 HTTP 请求头部被发送。
-
对
OPTIONS
请求的特殊处理:- 这一部分针对 CORS 预检请求,当浏览器发出
OPTIONS
请求时,Nginx 配置如何响应。 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';
:指定允许的头部列表,这允许浏览器在实际请求中携带这些头部。add_header 'Access-Control-Max-Age' 1728000;
:指定浏览器可以缓存预检请求结果的时间,单位是秒。这里设置的是 1728000 秒,相当于 20 天。add_header 'Content-Type' 'text/plain; charset=utf-8';
和add_header 'Content-Length' 0;
:设置响应类型和长度。return 204;
:返回 HTTP 状态码 204(无内容),表示预检请求成功,无需返回任何内容。
- 这一部分针对 CORS 预检请求,当浏览器发出