Last modified 2010-02-24T02:40:52+01:00 ago

Varnish and Drupal

Using Varnish with  Drupal prior to version 7 will require the use of  Pressflow, which backports Drupal 7's lazy session creation and other important performance enhancement. Without this, Drupal will create a PHP session cookie for all users, meaning Varnish is reduced to caching static files only. Luckily, Pressflow is a drop-in replacement for Drupal 6 (or even 5), which should be compatible with most modules and sites.

Once you have Pressflow (or Drupal 7) up and running, your VCL will probably want to have something like this:

sub vcl_recv {
  // Remove has_js and Google Analytics __* cookies.
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|has_js)=[^;]*", "");
  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  // Remove empty cookies.
  if (req.http.Cookie ~ "^\s*$") {
    unset req.http.Cookie;

  // Cache all requests by default, overriding the
  // standard Varnish behavior.
  // if (req.request == "GET" || req.request == "HEAD") {
  //   return (lookup);
  // }

sub vcl_hash {
  if (req.http.Cookie) {
    set req.hash += req.http.Cookie;

The above is borrowed wholesale from the  Four Kitchens wiki, which also has a handy  Pressflow/Drupal comparison chart.

There is also a  Varnish module which will allow you to set long object lifetimes, and use Drupal's existing cache expiration logic to dynamically purge Varnish when things change.

For a more complex working example of implementing Drupal with Varnish (as well as other high-performance best-practices) see this  in-depth install HOWTO on the Project Mercury (drupal+varnish) group.