如何根据请求中的 Origin 标头将 nginx Access-Control-Allow-Origin 正确设置为响应标头? [英] How to properly setup nginx Access-Control-Allow-Origin into response header based on the Origin header from the request?

查看:45
本文介绍了如何根据请求中的 Origin 标头将 nginx Access-Control-Allow-Origin 正确设置为响应标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个 nginx 配置设置,它将 Access-Control-Allow-Origin 设置为 Origin 中收到的值.

I am looking for a nginx config setup that does setup the Access-Control-Allow-Origin to the value received in the Origin.

似乎 * 方法不适用于 Chrome,多个 URL 不适用于 Firefox,因为 CORS 规范不允许这样做.

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.

到目前为止,唯一的解决方案是将 Access-Control-Allow-Origin 设置为在源中收到的值(是的,可以实施一些验证).

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).

问题是如何在 nginx 中做到这一点,最好不要安装额外的扩展.

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;

推荐答案

使用 if 有时会破坏其他配置,例如 try_files.您最终可能会遇到意外的 404.

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;
    }
    ...
 }

如果是邪恶的

这篇关于如何根据请求中的 Origin 标头将 nginx Access-Control-Allow-Origin 正确设置为响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆