我在将 CORS 策略添加到我的 NGINX 服务器时遇到了困难。我已将 DNS 服务器指向服务器,但 CORS 策略中的问题不起作用。访问 subdomain.domain.com 时一切正常,但问题出在位置块上。域/路径给出 CORS 策略错误。有什么办法可以解决这个问题吗?
no font @has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
答案1
好吧,你已经收到了一个答案——总比没有好,但在我看来,它的代码只能用作初始迭代。
下面的代码,我不是原作者(在 GitHub 上找到的 gist)在处理 CORS 方面要好得多。尤其在不使用通配符方面更胜一筹。仍有一些地方需要改进,但我正在使用它。
set $cors '';
# Extend the list of XSS-whilelisted domains by adding more
if ($http_origin ~ '^http[s]*?://(foo\.bar|.+\.foo\.bar|fou\.baar|.+\.fou\.baar)') {
set $cors T;
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}O";
}
if ($cors = 'T') {
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, DELETE, 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;
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#add_header 'Access-Control-Expose-Headers' 'Authorization' always;
}
if ($cors = 'O') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($cors = 'TO') {
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, DELETE, 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;
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
答案2
您可以在这里找到大量有关如何在 nginx 上启用 CORS 的信息,其中包括配置示例和大量背景信息:https://enable-cors.org/server_nginx.html