Caching a Wildcard Domain Using Varnish with Multiple Virtual Hosts

At my company, TGFI, we have a handful of sites that run through Varnish to cache images, css, javascript and even full pages in memory. To date, all of this had been done with known domains (domain.host, www.domain.host). This week, however, we have a new application going live in the system that uses a wildcard domain. Despite looking around, I was unable to find documentation on how to handle a wildcard domain when varnish is setup to handle multiple sites.

After a bit of playing around, here’s an example of how I ended up doing it:


backend backend1 {
  .host = "192.168.1.101";
}

backend backend2 {
  .host = "192.168.1.102";
}
backend backend3 {
  .host = "192.168.1.103";
}

# This allows you to hit multiple backends with one domain to balance across servers.
director director1 round-robin {
  { .backend = backend1; }
  { .backend = backend2; }
}

sub vcl_recv {

  # This site uses a director to hit multiple backend servers.
  if (req.http.host ~ "^www.domain1.com$" || req.http.host ~ "^domain1.com$") {
    set req.backend = director1;
  }

  # This site uses a wildcard domain to hit just one server. This is all RegEx based.
  if (req.http.host ~ "^domain2.com$" || req.http.host ~ "^.+\.domain2.com$") {
    set req.backend = backend3;
  }

}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.