Php – How to cache websites using Varnish, PHP and Cookies

cookiesPHPvarnish

I consider starting using Varnish on my websites. I just tried out Varnish and I am wondering how to cache pages even if I my websites uses cookies, for Google Analytics. I am trying to remove them but it seems like Varnish isn't caching. This is how my config looks like; http://pastie.org/1254664. If it matters I have one Debian server, and one server using Ubuntu Server. So, how do I cache the website even if I am using cookies?

Thank you in advance!

Addition: I don't get any X-Cache: HIT/MISS neither. What am I doing wrong?

Best Answer

I am fairly new to caching with Varnish, but here is what I've learned so far: There are several factors to consider when using Varnish for caching against an application.

In your case, know what cookies are being set and for what purpose. If varnish sees a cookie with your request, you will be passed to the backend, resulting in a cache miss.

Google Analytics Cookies

If you are using Google Analytics cookies, you can safely unset them in Varnish; don't worry, you will still the data in your GA reports. Use something like this in your vcl_recv

set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|__utma_a2a)=[^;]*", "");

You can try a couple more cleanup lines, also in the vcl_recv

Remove ";" prefixes from Cookies

set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");

Unset empty cookies

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

Application Specific Cookies

If your application sets a cookie when a user logs in to perform a function, those requests should not be cached and sent to the backend directly. Otherwise, you could cached pages viewed by logged in users (bad).

Use something like this:

if (req.http.Authorization || req.http.Cookie) {
  return (pass);
}

HTH & good luck.

Edit

Use this to see what cookies varnish is seeing come through:

varnishtop -i RxHeader -I Cookie

If you're regex misses any, catch 'em here!

Related Topic