Force redirect in Varnish

Loading

Sometimes in certain occasion you need to manage a complete redirection to an external site directly from Varnish.

Following you will find how to implement this using Varnish 4.0 and some specific rules in the VCL.


sub force_redirect {
   set req.http.host = "www.atomictag.com";
   return(synth(750, "Force redirection to external site."));
}

sub vcl_recv {
   # Force redirect
   call force_redirect;
   # Everything else will be ignored
}

sub vcl_synth {
   # Managing redirection
   if (resp.status == 750) {
      set resp.status = 301;
      set resp.http.Location = "http://www.atomictag.com/";
      return(deliver);
   }
}

Of course you can easily add more intelligence to the VCL, e.g.: by evaluating the redirection based on the http referrer or on a specific hostname.