wiki:VCLExampleRedirectInVCL

Redirecting using VCL

If you, for some reason, don't want to redirect on the back end, but prefer to do it in VCL, you can do it using one of the following recipes:

Redirect if the user agent matches a regex

sub vcl_recv {
   if (req.http.user-agent ~ "iP(hone|od)") {
      error 750 "Moved Temporarily";
   }
}
 
sub vcl_error {
    if (obj.status == 750) {
        set obj.http.Location = "http://www.example.com/iphoneversion/";
	set obj.status = 302;
        return(deliver);
    }
}

Redirect if the user agent matches a regex (multiple sites)

sub vcl_recv {
   if (req.http.user-agent ~ "lwp") {
      if (req.http.host ~ "example.com") {
          error 750 "example.com";
      } else {
          error 750 "localhost";
      }
   }
}
 
sub vcl_error {
    if (obj.status == 750) {
        if (obj.response ~ "example.com") {
            set obj.http.Location = "http://www.example.com/customversion";
	} elsif (obj.response ~ "localhost") {
            set obj.http.Location = "http://localhost/customversion";
	}
	set obj.status = 302;
        return(deliver);
    }

Redirect if the URL matches a regex

The redirection of a single or multiple sites by URL can also be accomplished in a generic way:

sub vcl_recv {
    if (req.http.host ~ "^(www\.)?oldexample\.com$") {
        error 750 "http://www.example.com/newlocation";
    } else if (req.http.host ~ "^(www\.)?ancientexample\.com$") {
        error 750 "http://newsite.com/ancient";
    }
}

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

Redirect to HTTPS, aka "Enforcing SSL behind an SSL termination point"

Useful when you want to redirect the clients to an SSL-version of your site, given that your varnish instance is running behind some SSL-termination point, such as a nginx instance with SSL enabled.

sub vcl_recv {
    if ( (req.http.host ~ "^(?i)somesite.org" || req.http.host ~ "^(?i)www.somesite.org")
         && req.http.X-Forwarded-Proto !~ "(?i)https") {
        set req.http.x-Redir-Url = "https://www.somesite.org" + req.url;
        error 750 req.http.x-Redir-Url;
    }
}

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