Virtual hosts in Varnish

 Virtual hosts are built into Varnish Cache. In fact they are so deeply built into it that sometimes it's a bit hard to actually figure out how it works. For Varnish an URL is an URL, whatever the host is. So, if you want to have special configuration based on what the host, either virtual or IP-based, is you have to write special configuration to do so.

Yesterday, Michael Alger, posted to the varnish-misc list with a good pattern on how to organize your VCL according to the host. The idea is simple, first lets take a look at IP-based configuration. Basically you put each configuration in one file and then you do if-elsif that include one file for each host. Like this:

 if (server.ip == "10.22.152.11")
 {
   include "/etc/varnish/site-something.com.vcl";
 }
 elsif (server.ip == "10.22.152.25")
 {
   include "/etc/varnish/site-somethingelse.com.vcl";
 }
 elsif (server.ip == "10.22.152.21")
 {
   include "/etc/varnish/site-anotherthing.com.vcl";
 }

For name-based virtual hosting, you'll probably want to first sanitise the host header (remove or add ":80" suffix, remove or add "www." prefix) and then include a site configuration based on the hostname requested:

 
if (! req.http.Host)
 {
   error 404 "Need a host header";
 }
 set req.http.Host = regsub(req.http.Host, "^www\.", "");
 set req.http.Host = regsub(req.http.Host, ":80$", "");

 if (req.http.Host == "something.com")
 {
   include "/etc/varnish/site-something.com.vcl";
 }
 elsif (req.http.Host == "somethingelse.com")
 {
   include "/etc/varnish/site-somethingelse.com.vcl";
 }

Thanks to for Michael Alger for his informative post.

The picture is taken by Flickr user Schristia and used under a CC licence. 

Edit:2010-12-16 Replaced = with == in the if req.http.Host statment.

 

25/11/10 11:19 by Per Buer

All things Varnish related

The Varnish blog is where the our team writes about all things related to Varnish Cache and Varnish Software...or simply vents.

SUBSCRIBE TO OUR BLOG

Posts by Topic

see all