Virtual hosts

Michael Alger varnish at mm.quex.org
Wed Nov 24 06:26:07 CET 2010


On Wed, Nov 24, 2010 at 12:00:28AM -0500, Ruslan Sivak wrote:
> Is there any sort of notion of virtual hosts in varnish?  How would I
> go about separating the config for different sites, or does everything
> need to go into one giant vcl file?

Yes and no. As far as Varnish is concerned, it has one config file.
However you can use "include" statements in the main config file to
insert the contents of other files at any point in the configuration, so
you can split it up between as many separate files as you like.

For my configuration, I have /etc/varnish/main.vcl which provides the
overall processing. This includes a few other files. At the very start,
I pull in /etc/varnish/acls.vcl - which just provides a central place to
define any ACLs which are used anywhere else in the config.

I also pull in a file /etc/varnish/inc-backends-prod.vcl which itself
simply includes a bunch of other files, with each file defining one set
of backends and accompanying directors.

So, you can split up the config however it suits you to do so.

If you want to do IP-based virtual hosting, you'll likely want to set up
a file that looks something like:

  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";
  }
  ...

Alternatively you can use regular expressions to match the hostname, or
any other fields you want to use to select the configuration to use.

I actually use a mix, with each main website on a dedicated IP address,
and then another shared IP for vanity domain name redirects and that
kind of thing.

Too long? Use  include "/some/file.vcl";  to bring in an additional file
at any point in the configuration, and structure those files however you
like.




More information about the varnish-misc mailing list