Mobile device detection with Varnish

As I already have blogged before, if you are using Varnish as a page caching mechanism, Drupal cannot be used to detect the device that is visiting your website.

Already some examples have been created to detect devices in Varnish and add a header string that allows the Drupal backend to know about the device type.

This is just a small snippet that I use to redirect mobile users to a mobile url and desktop users to the desktop url.

# vcl_recv routine
sub vcl_recv {
  call device_detection;
 
# other site specific vcl rules follow here
 
}
 
# Routine to try and identify device
sub device_detection { 
	# Default to thinking it's a PC
	set req.http.X-Device = "pc"; 
 
	# Add all possible agent strings
 
	# These are the most popular agent strings
	if (req.http.User-Agent ~ "iP(hone|od)" || req.http.User-Agent ~ "Android" || req.http.User-Agent ~ "Symbian" || req.http.User-Agent ~ "^BlackBerry" || req.http.User-Agent ~ "^SonyEricsson" || req.http.User-Agent ~ "^Nokia" || req.http.User-Agent ~ "^SAMSUNG" || req.http.User-Agent ~ "^LG" || req.http.User-Agent ~ "	webOS") { 
	    set req.http.X-Device = "mobile"; 
	  }  
 
	# These are some more obscure agent strings
	if (req.http.User-Agent ~ "^PalmSource"){
	  set req.http.X-Device = "mobile"; 
	}
 
	# Decide if we need redirection
	if(req.http.X-Device == "mobile") {
	  if(req.http.host !~ "m.domain.ltd"){
		error 750 "m.domain.ltd";
	  }
	}
	else {
	  if(req.http.host ~ "m.domain.ltd"){
	  	error 750 "www.domain.ltd";
	  }
	}
}
 
# Redirection routine
sub vcl_error {
  if (obj.status == 750) {
    if (obj.response ~ "m.domain.ltd") {
      set obj.http.Location = "http://m.domain.ltd" req.url;	
    } elsif (obj.response ~ "www.domain.ltd") {
      set obj.http.Location = "http://www.domain.ltd" req.url;
    }
    set obj.status = 302;
    return(deliver);
  }
}