Networking HowTos
Networking HowTos

Varnish with Multiple Backends

January 14, 2013 Linux

Varnish has the ability to reverse proxy to multiple backend servers if needed.
This howto guide outlines the configuration settings needed to redirect requests to different backends.
In our example, we have a web application backend (referenced to as “webapp”), and also a separate backend that just contains static content such as images, javascript, style sheets, etc. The static backend is just referenced as “static”. Both are running on port 8080.

Specifying the backend servers:

backend webapp {
    .host = "192.168.0.1";
    .port = "8080";
}
backend static {
    .host = "192.168.0.2";
    .port = "8080";
}

Specifying which backend to use:
We want all requests to go to the “webapp” backend by default, and only the static content to go to the “static” backend (images, style sheets, javascript, etc).

sub vcl_recv {
    set req.backend = webapp;
    if (req.url ~ "\.(js|css|swf|ico|jpg|jpeg|gif|png)$) {
        set req.backend = static;
    }
}

This sets the backend to “webapp” initially. If the request is for a static item on the site and matches the regular expression above, the backend setting gets changed to the “static” backend. If its not a static item, the backend remains as “webapp”.
Determine which backend is being used and if a cached copy was used:
You have the ability to set a HTTP header for debugging purposes to allow you to see which backend was used to process the request.

sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT " + req.backend;
    } else {
        set resp.http.X-Cache = "MISS " + req.backend;
    }
 }

If you look at the headers returned back to the client browser, you will be able to use the X-Cache header value to determine if the item was requested from the cache or not (if obj.hits is greater than 0, it came from the cache, and will display as “HIT”. If the request wasn’t in the cache, it will display “MISS”), and also will tell you which backend the request went to (or would have gone to). If you want to use the backend server’s host name instead of the backend name, replace “req.backend” with “server.hostname”.

You Might Also Like