Home About Blog

How do I create a redirect in VCL?

It’s really helpful to use VCL to create redirects as these requests will never hit your origin server, and be a lot quicker due to Varnish’s synthetic responses. We will be using the code blocks vcl_recv and vcl_synth for this task. In this example I will be redirecting http://www.test.com/abc to http://www.test.com/xyz.

First we want to check for our use case in vcl_recv.

if (req.url == "/abc" && req.http.host == "www.test.com") {
    return (synth(851, "Redirect"));
}

This piece of code is saying: If the url strictly equals /abc and the host header strictly equals www.test.com then return a synthetic response with status of 801 and reason of Redirect.

Next we want to capture the response in vcl_synth and set the redirect headers.

if (resp.status == 851) {
    set resp.http.Location = "http://www.test.com/xyz";
    set resp.status = 301;
    return (deliver);
}

This piece of code is saying: If the response status is strictly equal to 851 then set the location header equal to http://www.test.com/xyz, set the response status equal to 301, and deliver the response to the client.

Note: Keep in mind the status code of 301 is cached by the browser because it’s definition means MOVED PERMANENTLY, whereas the status code of 302 is not cached because it’s definition means MOVED TEMPORARILY.

1 Like

There’s a typo in the paragraph after the first code block. “status of 801” should be “status of 851”.