如何防止cookies被删除

how to prevent cookies from being deleted

if (req.http.Cookie !~ "(^|;\s*)(province=(.*?))(;|$)") {
   return (pass);
}

if (req.http.Cookie) {
  set req.http.Cookie = ";" + req.http.Cookie;
  set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
  set req.http.Cookie = regsuball(req.http.Cookie, ";(allgroups|viewed-products)=", "; =");
  set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
  set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");

  if (req.http.Cookie == "") {
    unset req.http.Cookie;
  }
}

我需要防止第一个 cookie 被删除,我注意到清漆出于某种原因不断删除我所有的 cookie,所以我想知道到底发生了什么,所以我检查了一下,我认为后一部分在错误,所以我是否需要通过执行以下操作来防止设置和取消设置的发生?

if (req.http.Cookie !~ "(^|;\s*)(province=(.*?))(;|$)") {
   return (pass);
}

if (req.http.Cookie) {
  set req.http.Cookie = ";" + req.http.Cookie;
  set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
  set req.http.Cookie = regsuball(req.http.Cookie, ";(allgroups|viewed-products|province)=", "; =");
  set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
  set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");

  if (req.http.Cookie == "") {
    unset req.http.Cookie;
  }
}

这是我将在您的案例中使用的代码片段,以防止删除以下 cookie:

  • 所有组
  • 浏览过的产品
sub vcl_recv {
    if (req.http.Cookie) {
        set req.http.Cookie = ";" + req.http.Cookie;
        set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
        set req.http.Cookie = regsuball(req.http.Cookie, ";(allgroups|viewed\-products|province)=", "; =");
        set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
        set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");
    
        if (req.http.cookie ~ "^\s*$") {
            unset req.http.cookie;
        }
    }
}

最后在所有cookie替换发生后cookie只是空白字符的集合,或者如果cookie是空字符串,我们删除整个cookie头。

当然,如果存在上述任何 cookie,情况就不会如此。

这真的可以解决问题。然而,我看到很多关于这种方法的混淆,这是理所当然的,因为这些正则表达式替换很难看且难以解释。

vmod_cookie

另一种方法是使用 vmod_cookie 并利用它提供的干净的 cookie 管理 API。有关文档,请参阅 http://varnish-cache.org/docs/6.6/reference/vmod_cookie.html

vmod_cookie is a native Varnish VMOD as of version 6.4. This means that versions 6.4, 6.5 and 6.6 ship it by default. If you're on an older version, you can compile the module from source by using https://github.com/varnish/varnish-modules

以下是您在案例中的使用方式:

import cookie;

sub vcl_recv {
    if (req.http.Cookie) {
        cookie.parse(req.http.cookie);
        cookie.keep("allgroups,view-products,province");
        set req.http.cookie = cookie.get_string();

        if (req.http.cookie ~ "^\s*$") {
            unset req.http.cookie;
        }
    }
}

查看最适合您的方法,但您必须承认 vmod_cookieregsub() 调用更易于使用和理解。