Wednesday, October 17, 2012

Varnish for multiple hosts, following redirects

Using Varnish 3.x for two servers, caching the remote one and following redirects internally.

backend default {
.host = "localhost";
.port = "8080";
}

backend backoffice {
    .host = "backoffice.example.net";
    .port = "80";
}

sub vcl_recv {

    if (req.http.host == "host.example.net") {
        #You will need the following line only if your backend has multiple virtual host names
        set req.http.host = "otherhost.example.net";
        set req.backend = backoffice;
        return (lookup);
    }
     set req.backend = default;
     return(pass);
}

sub vcl_fetch {
    if (beresp.status == 302) {
        set beresp.http.X-Magic-Redirect = "1";
        return(deliver);
    }
}

sub vcl_hit {
    if (obj.http.X-Magic-Redirect == "1") {
        set req.url = obj.http.Location;
        return (restart);
    }
}

sub vcl_deliver {
    if (resp.http.X-Magic-Redirect == "1") {
        unset resp.http.X-Magic-Redirect;
        return(restart);
    }
    return(deliver);
I am running my web server on port 8080 on the front facing server and on the default port 80 on for the backoffice one. Varnish will rewrite the host request to the corresponding virtual host on the backoffice, cache the results and even follow redirects without changing the URL line in the browser.

No comments:

Post a Comment