some blog : )

Varnish simple virtual hosts

Posted at — Dec 19, 2011

Situation with single Varnish instance used to handle multiple development environments for projects is usual and different projects could require different logic (for URL routing, processing, redirects, cache, etc).

One or three different configurations may be stored in default configuration file (default.vcl). But if count of configurations grows up, then file becomes unreadable and inconvenient.

I suggest to use a simple solution to split configurations to separate files and include them into main configuration file. It add some overhead for same configurations, but makes confuguration simplier to maintain.

At first, copy all subroutines of one project to separate file, under /etc/varnish/virtual-hosts/ (you may use other name for this folder), and name it with project identifier(for example, foobar.com.vcl)

Rename each subroutine in this vcl file with project identifier:

etc..

Then in main Varnish configuration file(in my example it is a default.vcl) add a include line with new file after backends and ACLs blocks:

include "/etc/varnish/virtual-hosts/example.com.vcl";

In each subroutine remove old statements and replace them with new “if-vhost-conditions” where custom routines will be invoded

sub vcl_recv {
    if (! req.http.Host)
    {
        error 404 "Need a host header";
    }

    if (req.http.Host == "example.com")
    {
    call foobar_vcl_recv;
    }
}

sub vcl_hash {
    if (req.http.Host == "example.com")
    {
    call foobar_vcl_hash;
    }
}

Repeat it for each project that need to be proxied with Varnish on your box and be happy : )

UPDATE: it is also possible to have separate VCL files using VCL labels since Varnish 5. Read more on info.varnish-software.com.