我尝试过使用一个非常流行的配置 https://gist.github.com/Stanback/7145487对于nginx,它启用了CORS并支持使用正则表达式进行源匹配。
这是我的配置:
server {
listen 80 default_server;
root /var/www;
location / {
if ($http_origin ~ '^http://(www\.)?example.com$') {
add_header Access-Control-Allow-Origin "$http_origin";
}
# Handling preflight requests
if ($request_method = OPTIONS) {
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
}
}
但是,此配置必须使用两个条件:一是匹配原始域名,二是捕获预检请求。因此,当第二个条件匹配时,第一个条件中的标头不会添加到响应中。
根据如果是邪恶 https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/官方文章,这是 nginx 的预期行为。
If If Is Evil
那么如何在 nginx 中启用 CORS 呢?或者也许有办法以某种方式克服这个限制?
您可以尝试使用map
而不是第一个if
block:
map $http_origin $allow_origin {
~^http://(www\.)?example.com$ $http_origin;
}
map $http_origin $allow_methods {
~^http://(www\.)?example.com$ "OPTIONS, HEAD, GET";
}
server {
listen 80 default_server;
root /var/www;
location / {
add_header Access-Control-Allow-Origin $allow_origin;
add_header Access-Control-Allow-Methods $allow_methods;
# Handling preflight requests
if ($request_method = OPTIONS) {
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
}
}
nginx 将拒绝添加空的 HTTP 标头,因此只有在以下情况下才会添加它们:Origin
标头存在于请求中并与此正则表达式匹配。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)