How to redirect non-www URLs to www in Varnish

Last Updated on

If a website's canonical URL has www, it is desirable, as a good SEO practice, to redirect the non-www URLs to www. That is, if the canonical URL is www.example.com, example.com should be redirected to www.example.com. How to do this when Varnish is listening on port 80 as a reverse HTTP proxy is given below in this post.

Solution

For Varnish 3.0

Add the following code in the file, /etc/varnish/default.vcl,

sub vcl_recv {
    if (req.http.host == "example.com") {
        set req.http.host = "www.example.com";
        error 750 "http://" + req.http.host + req.url;
    }
}

sub vcl_error {
    if (obj.status == 750) {
        set obj.http.Location = obj.response;
        set obj.status = 301;
        return(deliver);
    }
}

In the above code, you need to replace the two occurrences of example.com with the domain name of your website.

For Varnish 4.0

There are changes in VCL for Varnish 4.0, and the code to be added to /etc/varnish/default.vcl is,

sub vcl_recv {
    if (req.http.host ~ "^example.com") {
        return (synth (750, ""));
    }
}

sub vcl_synth {
    if (resp.status == 750) {
        set resp.status = 301;
        set resp.http.Location = "http://www.example.com" + req.url;
        return(deliver);
    }
}

As mentioned before, the two occurrences of example.com in the above code need to be replaced with the domain name of your website.