清漆:缓存OPTIONS / CORS请求

时间:2017-05-16 10:08:21

标签: caching cors varnish

正如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的正确缓存配置如何显示与相应的URL请求明显具有相同的HostIPHTTP GET?< / p>

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请求的一部分。

1 个答案:

答案 0 :(得分:2)

尝试以下方法。

要确保可以缓存OPTIONS请求方法,您需要从return程序中调用vcl_recv语句,以便built-in VCL&#39 ; s 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.
}
相关问题