【问题标题】:Varnish caching with cookies使用 cookie 进行清漆缓存
【发布时间】:2017-02-27 20:20:59
【问题描述】:

刚接触 Varnish。越来越难了,超出预期:-(

我正在尝试改进一些 php 代码,这些代码是不久前开发的,使用 varnish。 此代码仅使用两个 cookie:PHPSESSID 和 LANGUAGE

如果未定义,所有页面都会设置 PHPSESSID cookie。然而,这个用于匿名会话的 cookie 只在一页中使用。

假设我有 Page1、Page2、Page3 和 Page4。我的配置应该如下:

Page1、Page2 和 Page3 需要 LANGUAGE cookie 并应与该 cookie 一起缓存:每种语言和页面都有一个缓存。

Page4 需要 PHPSESSID 和 LANGUAGE cookie,不应缓存,因为它是针对每个用户的。

我的 default.vlc 工作不正常,所以任何方向都会非常感谢。也许我误解了一些概念。

    sub vcl_init {

    # When requests come to Varnish I need to remove PHPSESSID so it's not used for the hash in caching. Page4 doesn't need caching as it's specific for each user:
       if (req.http.host ~ "Page4") {
         return(pass);
       }

    # remove PHPSESSID so pages1, 2, and 3 get cached just once for everyuser but in all languages.

       if ((req.url !~ "page4")) {
          set req.http.Cookie = regsuball(req.http.Cookie, "PHPSESSID=[^;]+(; )?", "");
       }

   return (hash);


    }

我需要使用 LANGUAGE cookie 缓存网页,因此我将其包含在 vcl_hash 中:

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

  # hash cookies for requests that have them
  if (req.http.Cookie) {
    hash_data(req.http.Cookie);
  }
}

如何只删除 PHPSESSIONID?

sub vcl_backend_response {
  # Called after the response headers has been successfully retrieved from the backend.

  if (!(bereq.url ~ "Page4"))  {
     unset beresp.http.set-cookie;
  }
  return (deliver);

}

【问题讨论】:

    标签: varnish-vcl varnish-4


    【解决方案1】:

    你在正确的轨道上。如果我理解您的问题,那么不起作用的是您删除了所有 cookie 服务器响应(如果它不是 Page4),而不仅仅是删除 PHPSESSID。

    如果 url 不是 Page4,您可以在 sub vcl_backend_response 中执行正则表达式以仅删除 phpsessionid。

    beresp.http.set-cookie = regsuball(beresp.http.set-cookie, "PHPSESSID=[^;]+(; )?", "")
    

    或者,如果您使用 varnish 4 或更高版本,您应该使用 vmod cookie,这使得 cookie 处理更加容易(不再需要正则表达式)。

    【讨论】:

      猜你喜欢
      • 2017-01-09
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2018-09-12
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      相关资源
      最近更新 更多