【发布时间】:2021-09-02 14:57:21
【问题描述】:
我有一个用作 API 的 Symfony 5.2 应用程序,但我遇到了 Nelmio CORS 捆绑包的 CORS 问题。 该应用程序适用于某些客户(对我而言),其中一些客户在 Chrome 上面临这个 CORS 问题:
“对 XMLHttpRequest 的访问已被 CORS 策略阻止”请求的资源上不存在“Access-Control-Allow-Origin”标头
我不明白的是,它适用于某些设备/网络,而不适用于其他设备/网络。
我的 CORS_ALLOW_ORIGIN 环境变量:
CORS_ALLOW_ORIGIN: ^https?://(www\.example.com|example.com)(:[0-9]+)?$
我的 nelmio_cors 配置文件:
nelmio_cors:
defaults:
origin_regex: true
allow_origin: []
allow_methods: []
allow_headers: []
expose_headers: []
max_age: 0
hosts: []
forced_allow_origin_value: ~
paths:
'^/v([0-9\.]+)/':
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization', 'X-Auth-Api', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials']
expose_headers: ['Link']
max_age: 3600
我观察到标头被发送了两次,我认为是由于 nginx 配置与 nelmio_cors 冲突:
access-control-allow-credentials: true
access-control-allow-headers: content-type, authorization, x-auth-api, access-control-allow-origin, access-control-allow-credentials
access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With
access-control-allow-methods: GET, OPTIONS, POST, PUT, PATCH, DELETE
access-control-allow-methods: GET, POST, PUT, DELETE, OPTIONS
access-control-allow-origin: https://example.com
位于 symfony 文件夹中的 nginx.conf :
server {
listen 80;
server_name _;
charset utf-8;
client_max_body_size 2M;
sendfile off;
root /app/public;
index index.php;
#Nginx RealIP
set_real_ip_from 0.0.0.0/0;
real_ip_header CF-Connecting-IP;
real_ip_recursive on;
#Nginx RealIP
error_log /dev/stderr;
access_log /dev/stdout mainup;
#add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS, PATCH' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param HTTP_HOST $host;
}
location ~ /\.(ht|svn|git) {
deny all;
}
}
这可能是问题吗?我该如何解决这个问题?
【问题讨论】:
标签: symfony cors nelmiocorsbundle