【发布时间】:2021-07-12 00:08:52
【问题描述】:
我有一个从 CDN 请求静态文件的站点。许多文件可以在网站上使用,但有些文件被 CORS 政策阻止。
它阻止了 html、json、woff 和 woff2 文件,但让所有其他文件通过,包括 js、css、jpg 等。
这是一个使用 nginx 的 Magento 2 站点。这是我添加了 Access-Control-Allow-Origin 的 nginx.conf 文件:
location /static/ {
# Uncomment the following line in production mode
# expires max;
# Remove signature of the static files that is used to overcome the browser cache
location ~ ^/static/version\d*/ {
rewrite ^/static/version\d*/(.*)$ /static/$1 last;
}
location ~* \.(ico|jpg|jpeg|png|gif|svg|svgz|webp|avif|avifs|js|css|eot|ttf|otf|woff|woff2|html|json|webmanifest)$ {
add_header Cache-Control "public";
add_header X-Frame-Options "SAMEORIGIN";
include /etc/nginx/magento2-cors.conf;
expires +1y;
if (!-f $request_filename) {
rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
}
location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
add_header Cache-Control "no-store";
add_header X-Frame-Options "SAMEORIGIN";
include /etc/nginx/magento2-cors.conf;
expires off;
if (!-f $request_filename) {
rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
}
if (!-f $request_filename) {
rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
add_header X-Frame-Options "SAMEORIGIN";
include /etc/nginx/magento2-cors.conf;
}
这里是 magento2-cors.conf:
add_header 'Access-Control-Allow-Origin' '*' 'always';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' 'always';
add_header 'Access-Control-Allow-Headers' 'x-requested-with' 'always';
add_header 'Access-Control-Max-Age' 86400 'always';
add_header 'Content-Length' 0 'always';
return 204;
}
我不明白为什么 CORS 会阻止某些文件而不是其他文件。所有文件都通过同一个 CDN 进入。它们都来自静态目录,这就是上面的 nginx.conf 所引用的。 js 和 css 与 html 和 woff 位于同一块中,但它们不会被阻止,而 html 和 woff 是。
我已经刷新了浏览器缓存和 magento 缓存。我已经多次重启nginx,似乎没有任何效果。
【问题讨论】:
-
js、css、jpg 案例之所以成功,是因为它们可能是使用 HTML 标记中的
<script>、<link>和<img>元素发出的请求——而浏览器不强制执行相同的—— HTML 标记中<script>、<link>和<img>元素的原始策略。相反,json 案例失败了,因为它可能是由前端 JavaScript 代码生成的,在这种情况下,浏览器会强制执行同源策略。并且 woff 案例失败了,因为在这种特殊情况下,浏览器也会执行同源策略(与<script>、<link>和<img>案例不同)。 -
您可能想要更新问题以显示一些未按预期工作的前端代码,以及浏览器在 devtools 控制台中记录的确切错误消息。鉴于阻塞不会发生在服务器端(浏览器正在为所有请求发送响应),重要的是发出请求的上下文 - 具体来说,请求是由前端 JavaScript 代码发出还是由从 HTML 标记启动。