Javascript 如何根据请求中的 Origin 标头将 nginx Access-Control-Allow-Origin 正确设置为响应标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14499320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request?
提问by sorin
I am looking for a nginx config setup that does setup the Access-Control-Allow-Originto the value received in the Origin.
我正在寻找一个 nginx 配置设置,它确实Access-Control-Allow-Origin将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.
该*方法似乎不适用于 Chrome,并且多个 URL 不适用于 Firefox,因为 CORS 规范不允许这样做。
So far, the only solution is to setup the Access-Control-Allow-Originto the value received in the origin (yes some validation could be implemented).
到目前为止,唯一的解决方案是将 设置为Access-Control-Allow-Origin在源中接收到的值(是的,可以实施一些验证)。
The question is how to do this in nginx, preferably without installing additional extensions.
问题是如何在 nginx 中做到这一点,最好不要安装额外的扩展。
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;
回答by phylae
Using ifcan sometimes break other config such as try_files. You can end up with unexpected 404s.
使用if有时会破坏其他配置,例如try_files. 您最终可能会遇到意外的 404。
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;
}
...
}
回答by Mnebuerquo
I'm starting to use this myself, and this is the line in my current Nginx configuration:
我自己开始使用它,这是我当前 Nginx 配置中的一行:
add_header 'Access-Control-Allow-Origin' "$http_origin";
This sets a header to allow the origin of the request as the only allowed origin. So where ever you are coming from is the only place allowed. So it shouldn't be much different than allowing "*" but it looks more specific from the browser's perspective.
这将设置一个标头以允许请求的来源作为唯一允许的来源。所以无论你来自哪里,都是唯一允许的地方。所以它应该与允许 "*" 没有太大区别,但从浏览器的角度来看它看起来更具体。
Additionally you can use conditional logic in your Nginx config to specify a whitelist of hostnames to allow. Here's an example from https://gist.github.com/Ry4an/6195025
此外,您可以在 Nginx 配置中使用条件逻辑来指定允许的主机名白名单。这是来自https://gist.github.com/Ry4an/6195025的示例
if ($http_origin ~* (whitelist\.address\.one|whitelist\.address\.two)$) {
add_header Access-Control-Allow-Origin "$http_origin";
}
I plan to try this technique in my own server to whitelist the allowed domains.
我计划在我自己的服务器中尝试这种技术,将允许的域列入白名单。

