Http

使用“Set-Cookie”標頭清漆記憶體響應

  • April 20, 2017

我有一個頁面,它根據 URL 發送類似語言的“Set-Cookie”標頭。問題是這個頁面會獲得相當高的命中率,但現在還不能去掉“Set-Cookie”標題以便 Varnish 4 記憶體它。

該文件僅顯示如何unset beresp.http.set-cookie或我可以將 cookie 添加到帶有hash_data(req.http.cookie). 據我所知,將 cookie 添加到雜湊僅適用於請求 Cookie,而不適用於後端設置的 cookie。

我很確定vmod_header可能是解決方案的一部分,但我將如何使用它來記憶體我匹配的 cookieberesp.http.Set-Cookie == "language=en_us; path=/; domain=mydomain.tld"並記憶體此響應?

我最終解決了這樣的問題:

...
# The data on which the hashing will take place
sub vcl_hash {
 hash_data(req.url);
 if (req.http.host) {
       hash_data(req.http.host);
 } else {
       hash_data(server.ip);
 }

 # If the client supports compression, keep that in a different cache
 if (req.http.Accept-Encoding) {
       hash_data(req.http.Accept-Encoding);
 }

 # We add the cookie in the mix with the hash because we actually set cr_layout
 # It should be OK in this particular instance if the number of cookies will not grow
 hash_data(req.http.Cookie);
 return (lookup);
}

# This function is used when a request is sent by our backend
sub vcl_backend_response {
 # If we find our layout cookie we copy it to a header and then we remove it so we can cache the page
 # Later after we deliver the page from cache we set the cookie from the header and then remove that header
 if ( beresp.http.Set-Cookie && beresp.http.Set-Cookie ~ "cr_layout" ) {
   set beresp.http.first-visit = beresp.http.Set-Cookie;
   unset beresp.http.Set-Cookie;
 }
}

sub vcl_deliver {
 # We found that we created a header earlier to remove the cr_layout cookie temporary
 # Now we create that cookie again and remove the header.
 if (resp.http.first-visit) {
   set resp.http.Set-Cookie = resp.http.first-visit;
   unset resp.http.first-visit;
 }
}

記憶體鍵(也就是在 hash_data 中計算的雜湊)是在接收請求時創建的。尚未收到來自伺服器的響應。之後您無法更改它。

我可以看到的兩個選項是:

  • 要麼禁用帶有 Set-Cookie 標頭的響應記憶體(我認為這可能是由清漆的 defautl 完成的)
  • 或列出您在 Cookie 計算中使用的傳入請求中的參數(url、主機、接受語言…),並使用 hash_data 將它們添加到請求雜湊中

引用自:https://serverfault.com/questions/828452