wiki:VCLExampleRedirectInVCL

Version 4 (modified by tfheen, 3 years ago) (diff)

Add missing return, fixes #901

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);
    }
}