简体   繁体   中英

Codeigniter : Varnish and Cookie / Session conflict

I have a website which is dependent on session and cookie. I want to get Varnish cache implemented on it.

  1. When the browser is open the website has same session id, till the browser is closed. But the AGE value in header remains 0 . This AGE value describes if varnish is caching the page or not. 0 means its not caching.

  2. To check Varnish caching is working or not, curl -I domainname is the command, I hit this through terminal, The header gives different PHPSESSIONID on every HIT and the value of AGE also remains 0.

Can't exactly determine as in what is not allowing site to be cached by Varnish.

Just to test I commented the session_start() , and here are the following observation. On Browser

  1. The session id cookie was not created in browser.
  2. AGE still remained 0 for several hits on same page.

On Terminal

  1. The php session id was not shown in header response.
  2. Age value was 0 on first hit, but on later hits it kept getting incremental numeric value.

It seems that Varnish fails to cache on browser hits. Specially when Domain is specified.

Any Help How get the varnish cache working for session based website ?

Varnish does not cache pages that set cookies by default. There are two ways around this issue:

  1. Strip cookies from the page. This will only work for you if the page does not require a session in the first place (ie it has no user-specific content). You can do so like so:

     // ... default.vcl sub vcl_recv { unset req.http.Cookie; return(hash); } 
  2. Add the cookie to the hash generated by Varnish, which will then mean every session will have it's own individual cache (it'll still benefit performance, but nowhere near as significantly as if you can go for option 1. Like so:

     // ... default.vcl sub vcl_hash { hash_data(req.url); if (req.http.host) { hash_data(req.http.host); } else { hash_data(server.ip); } hash_data(req.http.Cookie); return(lookup); } 

You may have some pages that appear to have no user-specific content on (like say you have a blog, blog posts wouldn't need user-specific content) but you may have something that indicates whether or not the user is logged in. If you can make that happen over AJAX to a non-cached, or per-session cached endpoint then it'll all work fine.

With option 2, you may find you need to store the Cookie temporarily in another header so that Varnish actually caches the page, you can do so like this:

// ... default.vcl
sub vcl_recv {
  set req.http.X-Cookie = req.http.Cookie;
  unset req.http.Cookie;

  return(hash);
}

Then simply alter the vcl_hash function to use req.http.X-Cookie instead of req.http.Cookie .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM