【问题标题】:Varnish: Caching OPTIONS/CORS requestsVarnish:缓存 OPTIONS/CORS 请求
【发布时间】:2017-05-16 10:08:20
【问题描述】:

如documentation中所述,哈希键是根据请求的Host标头或IP和URL计算的:

sub vcl_hash {
    hash_data(req.url);
    if (req.http.host) {
        hash_data(req.http.host);
    } else {
        hash_data(server.ip);
    }
    return (lookup);
}

HTTP OPTIONS 的正确缓存配置看起来如何,显然与相应的 HTTP GET 请求具有相同的 URL、Host 或 IP?

curl -H "Origin: https://www.example.com" -I \
  -H "Access-Control-Request-Method: GET" \
  -X OPTIONS --verbose \
  https://backend.server.example/rest/endpoint

另外,最好缓存与 Origin 标头有关的响应,该标头也是 CORS 请求的一部分。

【问题讨论】:

    标签: caching cors varnish


    【解决方案1】:

    试试下面的。

    为了确保OPTIONS 请求方法可以被缓存,您需要从您的vcl_recv 过程中调用return 语句,这样built-in VCL 的vcl_recv 根本不会运行。并对其进行一些更改:

    sub vcl_recv {
        if (req.method == "PRI") {
        /* We do not support SPDY or HTTP/2.0 */
        return (synth(405));
        }
        if (req.method != "GET" &&
          req.method != "HEAD" &&
          req.method != "PUT" &&
          req.method != "POST" &&
          req.method != "TRACE" &&
          req.method != "DELETE") {
            /* Non-RFC2616 or CONNECT which is weird. */
            return (pipe);
        }
    
        if (req.method != "GET" && req.method != "HEAD" && req.method != "OPTIONS") {
            /* We only deal with GET and HEAD by default */
            return (pass);
        }
        if (req.http.Authorization || req.http.Cookie) {
            /* Not cacheable by default */
            return (pass);
        }
        if (req.method == "GET" || req.method == "HEAD" || req.method == "OPTIONS") {
            set req.http.x-method = req.method;
        }
        return (hash);
    }
    sub vcl_backend_fetch {
        set bereq.method = bereq.http.x-method;
    }
    

    为了使缓存根据 Origin 标头值不同,您将输入如下内容:

    sub vcl_hash {
    
        if (req.http.Origin) {
            hash_data(req.http.Origin);
        } 
        # no return here in order to have built-in.vcl do its default behavior of also caching host, URL, etc.
    }
    

    【讨论】:

    • 我试过了,但似乎为OPTIONS 请求启用缓存不知何故被转换为GET 后端提取。因此,与直接访问后端相比,当我通过清漆发出请求时,标头会有所不同。有什么想法吗?
    • 当你在return(hash) 中vcl_recv 时,Varnish 似乎会将请求转换为GET ...我会用绕过它的技巧来更新答案。
    猜你喜欢
    • 1970-01-01
    • 2015-06-11
    • 2015-03-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2016-06-28
    • 2014-04-09
    相关资源
    最近更新 更多