April 27, 2016

Expanding Varnish to Serve Mutiple Languages

Varnish is often used with PHP or NodeJS. On my server I run both applications simultaneously. Its possible to run NodeJS and PHP applications through Nginx, send them to the same varnish instance by setting different backends. This is done by working with the Varnish configuration language (VCL) and is surprisingly simple. Its also not really talked about much so here is an example. My setup also serves SSL content taking into account not to cache the management interface which includes authentication tokens and the like. I also realise I should call it TLS not SSL. To keep it simple here is a diagram:

Diagram of Nginx, Varnish, PHP and NodeJS on different ports

To make the changes open the following file:

nano /etc/varnish/default.vcl

Below the default backend definition add the following:

backend ghost {
  .host = "";
  .port = "2368";

The above creates a second backend that is getting its content from our Ghost NodeJS app running on port 2363. Our PHP application is served by Nginx which would still be on the default backend.

Finally in the sub_vcl_recv section we need to tell Varnish which backend to use. Many advanced methods can be used but here is a simple example that sends the domain howson.me to the ghost cache and any other sites to the PHP cache:

if (req.http.host ~ "howson.me") {
    set req.backend_hint = ghost;
} else {
    set req.backend_hint = default;

There we have it. An easy way to use one varnish instance with multiple languages.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus