如何正确设置nginx Access-Control-Allow-Origin到响应头中根据请求的Origin头? [英] How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request?
问题描述
我正在寻找一个nginx配置设置,设置访问控制允许原始
到在原始 code>。
似乎 *
方法无法在Chrome和多个网址不能与Firefox一起使用,因为CORS规范不允许。
到目前为止,唯一的解决方案是设置 Access-Control-Allow-Origin
问题是如何在nginx中执行此操作,最好不安装其他扩展。
设置$ allow_originhttps://example.com
#而我想从Origin请求头获取值
add_header' Access-Control-Allow-Origin'$ allow_origin;
解决方案使用 if
有时可以破坏其他配置,如 try_files
。
map $ http_origin $ cors_header {
default;
〜^ https?:// [^ /] + \.example\.com(:[0-9] +)?$$ http_origin;
}
服务器{
...
位置/ {
add_header访问控制允许原因$ cors_header;
try_files $ uri $ uri / /index.php;
}
...
}
I am looking for a nginx config setup that does setup the Access-Control-Allow-Origin
to the value received in the Origin
.
It seems that the *
method doesn't work with Chrome and the multiple URLs doesn't work with Firefox as it is not allowed by CORS specification.
So far, the only solution is to setup the Access-Control-Allow-Origin
to the value received in the origin (yes some validation could be implemented).
The question is how to do this in nginx, preferably without installing additional extensions.
set $allow_origin "https://example.com"
# instead I want to get the value from Origin request header
add_header 'Access-Control-Allow-Origin' $allow_origin;
解决方案 Using if
can sometimes break other config such as try_files
. You can end up with unexpected 404s.
map $http_origin $cors_header {
default "";
"~^https?://[^/]+\.example\.com(:[0-9]+)?$" "$http_origin";
}
server {
...
location / {
add_header Access-Control-Allow-Origin $cors_header;
try_files $uri $uri/ /index.php;
}
...
}
这篇关于如何正确设置nginx Access-Control-Allow-Origin到响应头中根据请求的Origin头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!