NGINX proxy_pass、proxy_cache 和 CORS 不起作用

问题描述 投票:0回答:1

为什么当添加

add_header 'Access-Control-Allow-Origin' '*' always;
以允许任何 CORS 请求时,缓存在 nginx 中停止工作?

解决办法是什么?

    proxy_cache_path /tmp/nginx levels=1:2 keys_zone=dokku:10m inactive=60m use_temp_path=off;
    add_header X-Cache-Status \$upstream_cache_status;

    server {
        listen       8080;
        server_name  localhost;

        location / {
            # Proxy
            proxy_pass  http://0.0.0.0:3000/;

            # CACHE
            proxy_cache dokku; 

            # CORS
            add_header 'Access-Control-Allow-Origin' '*' always; # <-- Offending line
        }
    }
nginx cors nginx-reverse-proxy
1个回答
0
投票

发生此问题的原因是,当

Access-Control-Allow-Origin
标头设置为
*
时,它会使响应成为通配符 CORS 响应。
This means the response is not associated with any particular origin, which can prevent the browser from caching the response properly.

要解决此问题,您有以下几种选择:

指定允许的来源:

Instead of using a wildcard *, specify the exact origins that are allowed to access your resources
。这样,响应将与特定来源相关联,并且缓存应该按预期工作。

add_header 'Access-Control-Allow-Origin' 'http://example.com' always;

Vary 标头:如果您无法指定允许的来源并需要使用通配符,

you can add the Vary header to let caching systems know that the response should vary based on the Origin header
。这可能不适用于所有情况,但值得尝试。

add_header 'Vary' 'Origin' always;
add_header 'Access-Control-Allow-Origin' '*' always;
© www.soinside.com 2019 - 2024. All rights reserved.