检测 varnish hook 中的返回代码(模式)

检测 varnish hook 中的返回代码(模式)

vcl_recv我根据 cookie 是否存在来决定是否传递或者查找:

sub vcl_recv {
    if (req.http.Cookie ~ "(JSESSIONID=)" ) {
            /* do not cache logged in users */
            return (pass);
    }
    return (lookup);
}

vcl_fetch对一些页面的缓存进行了微调:

sub vcl_fetch {

    /* custom rules block */
    if (req.url ~ "^/foo") { set beresp.ttl=30s; }
    if (req.url ~ "^/bar") { set beresp.ttl=1m; }
    if (req.url ~ "^/123") { set beresp.ttl=10m; }

    return (deliver);
}

我如何知道vcl_fetch我是处于通过模式还是查找模式?如果我处于查找模式,我希望能够避免运行“自定义规则块”,因为登录的用户无论如何都会在通过模式下运行,因此这些规则不适用于他们。

答案1

您始终可以在 vcl_recv 中设置自定义标头:

sub vcl_recv {
  if (req.http.Cookie ~ "(JSESSIONID=)" ) {
    /* do not cache logged in users */
    set req.http.x-my-mark = "passed";
    return (pass);
  }
  return (lookup);
}
#...
sub vcl_fetch {
  if (req.http.x-my-mark == "passed") {
    /* custom rules block */
    if (req.url ~ "^/foo") { set beresp.ttl=30s; }
    if (req.url ~ "^/bar") { set beresp.ttl=1m; }
    if (req.url ~ "^/123") { set beresp.ttl=10m; }
  }

  return (deliver);
}

vcl_pass但我认为将您的登录名放在[1] 上或仅对 vcl_fetch 执行原始检查会更清楚:

sub vcl_fetch {
  if (req.http.Cookie ~ "(JSESSIONID=)") {
    /* custom rules block */
    if (req.url ~ "^/foo") { set beresp.ttl=30s; }
    if (req.url ~ "^/bar") { set beresp.ttl=1m; }
    if (req.url ~ "^/123") { set beresp.ttl=10m; }
  }

  return (deliver);
}

[1]https://www.varnish-software.com/static/book/VCL_functions.html#vcl-vcl-pass

相关内容