加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

php – NGINX’Access-Control-Allow-Origin’标头包含多个值

发布时间:2020-12-13 21:05:13 所属栏目:Nginx 来源:网络整理
导读:我有一个带PHP的NGINX服务器(我们假设主机名为http://myserver.com).我有一个PHP脚本,我通过XHR从我的localhost上的网页访问.我将它用作类似于freegeoip.net的GeoIP服务器. 我正在尝试将XHR锁定到特定域. 这是我的配置设置: location ~ .php${ try_files $

我有一个带PHP的NGINX服务器(我们假设主机名为http://myserver.com).我有一个PHP脚本,我通过XHR从我的localhost上的网页访问.我将它用作类似于freegeoip.net的GeoIP服务器.

我正在尝试将XHR锁定到特定域.

这是我的配置设置:

location ~ .php${
    try_files $uri =404;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;

    fastcgi_param GEOIP_COUNTRY_CODE $geoip2_data_country_code;
    fastcgi_param GEOIP_COUNTRY_NAME $geoip2_data_country_name;
    fastcgi_param GEOIP_COUNTRY_GEONAME_ID $geoip2_data_country_geoname_id;
    fastcgi_param GEOIP_CITY_NAME $geoip2_data_city_name;
    fastcgi_param GEOIP_CITY_GEONAME_ID $geoip2_data_city_geoname_id;
    fastcgi_param GEOIP_CONTINENT_CODE $geoip2_data_city_continent_code;
    fastcgi_param GEOIP_CONTINENT_GEONAME_ID $geoip2_data_city_continent_geoname_id;
    fastcgi_param GEOIP_LATITUDE $geoip2_data_city_location_latitude;
    fastcgi_param GEOIP_LONGITUDE $geoip2_data_city_location_longitude;
    fastcgi_param GEOIP_TIME_ZONE $geoip2_data_city_location_timezone;
    fastcgi_param GEOIP_ISP $geoip2_data_city_traits_isp;
    fastcgi_param GEOIP_IP_ADDRESS $geoip2_data_city_traits_ip_address;

    set $cors "";

    if ($http_origin ~* 'https?://(www.domain1.com|www.domain2.com)')
    {
        set $cors "true";
    }

    if ($cors = 'true')
    {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,Pragma,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
    }

    if ($request_method = 'OPTIONS')
    {
        return 204;
    }
}

我遇到的问题是,当我执行XHR请求时,我收到以下错误:

XMLHttpRequest无法加载http://myserver.com/. ‘Access-Control-Allow-Origin’标头包含多个值’*,http:// localhost’,但只允许一个.因此不允许Origin’http:// localhost’访问.

我只有一次调用add_header’Access-Control-Allow-Origin’“$http_origin”;在配置文件中,为什么我有多个值?有没有办法可以禁用第一个电话,即*?

1.)让应用程序动态批准并添加响应头.

$allowed_domains = ['http://allowed.com','http://another_allowed.com'];

function add_cors_header() {
    if (in_array($_SERVER['http_origin'],$allowed_domains)) {
        header('Access-Control-Allow-Origin',$_SERVER['http_origin']);
    }
}

2.)或者在启用Lua的情况下安装OpenResty版本的Nginx并执行相同操作,但在Nginx conf文件中使用Lua.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读