设置 Access-Control-Allow-Origin 时,来自 Origin 的 URL 已被 CORS 策略阻止

时间:2021-04-17 02:32:25

标签: nginx cors

我有一个从 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,似乎没有任何效果。

1 个答案:

答案 0 :(得分:-1)

不要使用include,看是否放入

add_header Access-Control-Allow-Origin *;

没有任何 if 语句就可以了。

在这行之后试试

location ~* \.(ico|jpg|jpeg|png|gif|svg|svgz|webp|avif|avifs|js|css|eot|ttf|otf|woff|woff2|html|json|webmanifest)$ {

您也可以尝试将字体放在子目录中(即:fonts),看看是否能改善您的情况。

如果这不起作用,请尝试将 * origin 标头紧跟在

location /static/ {

祝你好运!