Mobile redirects using Varnish

Our loadbalancers TMM has gone up quite a bit lately, so I started looking into how to move some of the workload to Varnish instead. I came across this configexample and pulled out the mobile redirects part. It’s a rather dirty hack, but it works. Varnish does not have support of HTTP redirects, so you have to trigger an error and then pick it up in the vcl_error subroutine later.
This is what the redirect-config looks like on my test-system :

sub vcl_recv {
if ( req.http.user-agent ~ "(.*Blackberry.*|.*BlackBerry.*|.*Blazer.*|.*Ericsson.*|.*htc.*
|.*Huawei.*|.*iPhone.*|.*iPod.*|.*MobilePhone.*|.*Motorola.*|.*nokia.*
|.*Novarra.*|.*O2.*|.*Palm.*|.*Samsung.*|.*Sanyo.*|.*Smartphone.*
|.*SonyEricsson.*|.*Symbian.*|.*Toshiba.*|.*Treo.*|.*vodafone.*
|.*Xda.*|^Alcatel.*|^Amoi.*|^ASUS.*
|^Audiovox.*|^AU-MIC.*|^BenQ.*|^Bird.*|^CDM.*|^DoCoMo.*|^dopod.*
|^Fly.*|^Haier.*|^HP.*iPAQ.*|^imobile.*|^KDDI.*|^KONKA.*|^KWC.*
|^Lenovo.*|^LG.*|^NEWGEN.*|^Panasonic.*|^PANTECH.*|^PG.*|^Philips.*
|^portalmmm.*|^PPC.*|^PT.*|^Qtek.*|^Sagem.*|^SCH.*|^SEC.*|^Sendo.*
|^SGH.*|^Sharp.*|^SIE.*|^SoftBank.*|^SPH.*|^UTS.*|^Vertu.*
|.*Opera.Mobi.*|.*Windows.CE.*|^ZTE.*)"
&& req.http.host ~ "(www.somehost.com)"
&& req.url == "/") {
set req.http.newhost = regsub(req.http.host, "(www)?\.(.*)", "http://m.\2");
error 750 req.http.newhost;
}


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

Be Sociable, Share!

Tags: , ,

6 Responses to “Mobile redirects using Varnish”

  1. bolav Says:

    Do you have an example that checks a cookie as well, so that you can choose to always have the website?

  2. morten Says:

    You could check for a cookie too, or you can just use something like ?nomobile in the url and then add to your vcl code something like :

    if ( req.http.url != “?nomobile” ) {
    # do all the redirect stuff
    }

  3. Daniel Says:

    Thanks for figuring this out!

    If anyone tries this, you now have to change

    deliver;

    to

    return(deliver);

  4. tigaszzz Says:

    That doesn’t work if you what something more persistent, you have to check for cookies with something like
    if (req.http.cookie ~ “NOMOBILE”) {

  5. Phoenix Says:

    Thank you so much for sharing your views.. Really I appreciate to you. but i wanna know another example of it can you please tell me another one?

    Phoenix

  6. small christmas tree dots Says:

    My brother suggested I might like this blog. He was totally right.
    This submit truly made my day. You cann’t believe just how a lot time I
    had spent for this information! Thanks!

Leave a Reply