Varnish How to redirect non-www URLs to www

From Brian Nelson Ramblings
Jump to: navigation, search

How to redirect non-www URLs to www in Varnish

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.briansnelson.com, example.com should be redirected to www.briansnelson.com. How to do this when Varnish is listening on port 80 as a reverse HTTP proxy.

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

Redirect from non-www to www

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

Now you will want to create the redirect

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

Redirect from www to non-www

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

Now you will want to create the redirect

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