我的目标是将对web应用程序的访问限制在没有原产地= http://localhost:3000的任何请求中。
因此,在互联网上搜索了一下之后,我找到了这个配置(嗯,复制粘贴):
location / {
set $cors '';
if ($http_origin ~ 'http://localhost:3000') {
set $cors 'true';
}
if ($cors = 'true') {
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, PUT, PATCH, DELETE, PATCH, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
}
if ($request_method = 'OPTIONS') {
# Tell client that this pre-flight info is valid for 20 days
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://10.131.20.142:8000/131j3yc1;
proxy_set_header received-from "nginx";
access_log /dev/stdout upstream_log;
}我对它进行了测试看看它的表现。当我用原始http://localhost:3000发送一个请求时,它会发送200个OK和CORS头。当我发送没有来源或不同来源的请求时,它仍然发送200个OK,但是没有CORS头。当浏览器获得带有CORS头的响应时,它可以正常工作,但是当CORS头不存在时,它会抛出如下异常:

我想了解这里的CORS配置保护是什么?
我猜想我的配置可能是错误的,因为它不能有效地保护应用程序免受跨源请求的影响,或者我对CORS的理解是不正确的。
有人能帮我弄清楚我在做什么/理解错了什么吗?
发布于 2018-05-05 18:08:07
尝试使用more_set_headers而不是add_header
more_set_headers 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, PATCH, OPTIONS';
more_set_headers 'Access-Control-Allow-Headers:Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With';
etcmore_set_headers指令是HttpHeadersMore模块的一部分,它包含在nginx的nginx-额外风味中,您可以通过以下操作在ubuntu16上安装它:
sudo apt-获取安装nginx-附加程序
https://stackoverflow.com/questions/49727301
复制相似问题