Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure multiple sites with Varnish

We have a server which needs to serve multiple domains though varnish e.g. example1.com, example2.com and example3.com

Our current .vcl file looks like this:

sub vcl_recv {   set req.http.Host = "example1.com";       lookup; } 

How do I set the correct req.http.Host for the correct incoming request?

like image 357
Tom Avatar asked Jul 26 '10 10:07

Tom


People also ask

What is Varnish configuration?

The Varnish Configuration Language (VCL) is a domain-specific programming language used by Varnish to control request handling, routing, caching, and several other aspects. At first glance, VCL looks a lot like a normal, top-down programming language, with subroutines, if-statements and function calls.

How does Varnish caching work?

Varnish cache is a web application accelerator also known as caching HTTP reverse proxy. It acts more like a middle man between your client (i.e. user) and your web server. That means, instead of your web server to directly listen to requests of specific contents all the time, Varnish will assume the responsibility.


2 Answers

You can support multiple frontend domains this way:

 backend example1 {      .host = "backend.example1.com";      .port = "8080";  }  backend example2 {       .host = "backend.example2.com";       .port = "8080";  }  sub vcl_recv {     if (req.http.host == "example1.com") {         #You will need the following line only if your backend has multiple virtual host names         set req.http.host = "backend.example1.com";         set req.backend = example1;         return (lookup);     }     if (req.http.host == "example2.com") {         #You will need the following line only if your backend has multiple virtual host names         set req.http.host = "backend.example2.com";         set req.backend = example2;         return (lookup);     }  } 
like image 52
Cristian Vidmar Avatar answered Sep 17 '22 13:09

Cristian Vidmar


I'm using setup similar to Cristian's, but in if clauses I match req.http.host against regular expression:

#for www.example.com or example.com if (req.http.host ~ "^(www\.)?example\.com$") {         set req.backend = example_com;         return (lookup); }  #with any subdomain support if (req.http.host ~ "^(.*\.)?example2\.com$") {         set req.backend = example2_com;         return (lookup); } 

Don't forget to set backends appropriately!

like image 38
msurovcak Avatar answered Sep 21 '22 13:09

msurovcak