Varnish URL Rewriting




Varnish the reverse proxy can do some pretty cool stuff. I just realized that it compiles its VCL rules into C so that they are process quite efficiently. Here’s a few examples:

Route to a different backend based upon location (i.e. url):

backend server1 {
    set backend.host = "192.168.222.222";
    set backend.port = "80";
}

sub vcl_recv {
    if (req.url ~ "^/location-url") {
        set req.backend = server1;
        set req.http.host = "www.example.com";
    }
}

Explanation: when a client requests the url “/location-url” from varnish, it “routes” the request server1, which is located at the ip address 192.168.222.222, and uses the http host name www.example.com.

Backend choice with a traditional rewrite:

backend server1 {
    set backend.host = "192.168.222.222";
    set backend.port = "80";
}

sub vcl_recv {
    if (req.url ~ "^/location-url") {
        set req.backend = server1;
        set req.url = regsub(req.url, "^/location-url", "/url-location");
        set req.http.host = "www.example.com";
    }
}

Explanation: this is the same example, but the request prefix is changed from location-url to url-location. Pretty nifty, huh?

2 Responses to “Varnish URL Rewriting”


  1. 1 Shahid

    I have an issue when backen port is set to 80.

    Varnish listen on port 6081 and the backend haproxy listen on port 80.

    Varnish is passing 6081 to backend.

    This is the varnish log

    12 RxRequest c GET
    12 RxURL c /frontend_dev.php/
    12 RxProtocol c HTTP/1.1
    12 RxHeader c Host: example.com:6081
    12 RxHeader c User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0
    12 RxHeader c Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    12 RxHeader c Accept-Language: en-us,en;q=0.5
    12 RxHeader c Accept-Encoding: gzip,deflate
    12 RxHeader c Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
    12 RxHeader c Keep-Alive: 300
    12 RxHeader c Connection: keep-alive
    12 RxHeader c Cookie: mobshare=954986349020f015115b99df238a8a75
    12 VCL_call c recv
    12 VCL_return c pass
    12 VCL_call c pass
    12 VCL_return c pass
    13 BackendOpen b default 127.0.0.1 51345 0.0.0.0 80
    13 BackendXID b 118910221
    12 Backend c 13 default
    13 TxRequest b GET
    13 TxURL b /frontend_dev.php/
    13 TxProtocol b HTTP/1.1
    13 TxHeader b Host: haproxy.com:6081
    13 TxHeader b User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0
    13 TxHeader b Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

  2. 2 Albert

    What does your VCL look like?

Leave a Reply