如何在 NGINX 中为所有域添加 CORS(跨源策略)?

How to add CORS (cross origin policy) to all domains in NGINX?

我创建了一个用于提供静态文件(CSS、图像、字体和 JS 等)的文件夹Magento 2 设置。

我想允许所有域通过 CORS 进行所有访问 - 跨源策略,我也想缓存数据。这就是我所拥有的。 (我不是在寻求关于 JSONP 问题的安全建议或提示 - 我想要全局访问文件目录)

location /cdn-directory/ {

    location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2|zip|gz|gzip|bz2|csv|xml)$ {
        add_header Cache-Control "public";
        add_header X-Frame-Options "ALLOW-FROM *";
        expires +1y;
    }

}

根据 documentation 它说 X-Frame-Options 支持 ALLOW-FROM uri 但看不到使用 * (所有域)或在此 [=14 中添加某些多个域的示例=].我需要允许所有域访问我的静态文件夹。

我没有在 nginx 上尝试过,但允许当前请求的来源在 tomcat:

中有效
add_header X-Frame-Options "ALLOW-FROM $http_origin";

允许所有域嵌入资源(例如,在 iframe 等中)是默认设置,因此不需要额外的 headers。

X-Frame-Options HTTP 响应 Header 的唯一目的是防止外部站点将交互式资源嵌入 iframe,因此如果您的意图是 ALLOW-FROM * (这确实不应该是一个有效的指令,如上所述),那么你应该完全忽略整个 header ,任何人都可以完全正确地访问你的静态资源随心所欲地来自任何域。

假设您确实需要 CORS(跨源请求共享),而不是仅仅嵌入到 iframe 中,配置将是:

location /cdn-directory/ {

    location ~* \.(js|css|swf|eot|ttf|otf|woff|woff2)$ {
        add_header Cache-Control "public";
        add_header Access-Control-Allow-Origin: *
        expires +1y;
    }

}
location /cdn-directory/ {

location ~* \.(js|css|swf|eot|ttf|otf|woff|woff2)$ {
    add_header 'Cache-Control' 'public';
    add_header 'X-Frame-Options' 'ALLOW-FROM *';
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    expires +1y;
  } 
}

http://enable-cors.org/server_nginx.html

这可能有点矫枉过正,但我​​在 Magento 1 上使用了以下 headers。8.x 安装 CORS:

add_header 'Access-Control-Allow-Origin' "*";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';