[英]Blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values
[英]NGINX 'Access-Control-Allow-Origin' header contains multiple values
我有一個帶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 cannot load http://myserver.com/. The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost', but only one is allowed. Origin 'http://localhost' is therefore not allowed access.
我只有一次調用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。
所以我犯的錯誤是我的PHP文件中有以下內容:
header('Access-Control-Allow-Origin: *');
我早點設置了它,忘記把它取出來。
現在一切都很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.