Web tech note–configuring Varnish 3 to cache with Drupal and WordPress

I am a fan of Varnish caching reverse proxy. It is running on the servier where this blog is hosted. In theory it is not very relevant for this site because I am using Cloudflare, a free CDN which claims to cache the website. I am not sure how how long they keep the cache, but every request I make for a page from a logged-out browser is in fact hitting my server, so server speed is important.

WordPress is anyway fast and offers sophisticated caching with the W3 Total Cache plugin (or various other plugins which are almost as effective and simpler to use), but nothing beats Varnish serving pages from the Varnish cache for speed, particulary if you have a busy site (as I hope Classics Blog will be: yes, a server technology which should stay reasonably functional for 1,000,000 page requests per day is a little excessive at present!).

My server has several Drupal sites on it, in particular an online shop I built for a bookseller friend, P J Hilton, so Varnish has to be configured to work with Drupal. Every time you upgrade Varnish, they seem to change the syntax of the configuration language, so you have to amend the config file, which is a pain. Anyway, now I am using the new Varnish 3, and have finally got it to work, using the VCL config file which can be downloaded here. The file is called drupal_trial because writing it has been a trial (I regret upgrading from Varnish 2, which was working fine). And because it is a work in progress, I am trying things out.

What about WordPress? WordPress seems to set a PHPSESSID cookie for non-logged-in users, and other cookies. In any event, the Drupal 6 and Drupal 7 sites were being cached nicely with this Varnish config, but I was struggling to get clssicsbog.net (on WordPress) to cache.

The quick and dirty solution was to strip all cookies for non-logged-in users on a per-URL basis (i.e. for http://classcsblog.net only).

Pop this into a Varnish config file basically written for Drupal:

# remove cookies for my WordPress site, normalize namespace first
if (req.http.host ~ “(?i)^(www.)?classcsblog.net”) {
set req.http.host = “classicsblog.net”;
}
if (req.http.host == “classicsblog.net”) {
if (!(req.url ~ “wp-(login|admin)”)) {
remove req.http.Cookie;
}
}

It works!

Leave a Reply

Your email address will not be published. Required fields are marked *