7

I need to redirect the traffic to one backend or another according to the user-agent. Is that the right thing to do ?

server {
    listen      80;
    server_name my_domain.com;

    if ($http_user_agent ~ iPhone ) {
        rewrite     ^(.*)   https://m.domain1.com$1 permanent;
    }
    if ($http_user_agent ~ Android ) {
        rewrite     ^(.*)   https://m.domain1.com$1 permanent;
    }
    if ($http_user_agent ~ MSIE ) {
        rewrite     ^(.*)   https://domain2.com$1 permanent;
    }
    if ($http_user_agent ~ Mozilla ) {
        rewrite     ^(.*)   https://domain2.com$1 permanent;
    }
}
Luc
  • 518
  • 3
  • 5
  • 21

2 Answers2

15

If you're using 0.9.6 or later, you can use a map with regular expressions (1.0.4 or later can use case-insensitive expressions using ~* instead of just ~):

http {
  map $http_user_agent $ua_redirect {
    default '';
    ~(iPhone|Android) m.domain1.com;
    ~(MSIE|Mozilla) domain2.com;
  }

  server {
    if ($ua_redirect != '') {
      rewrite ^ https://$ua_redirect$request_uri? permanent;
    }
  }
}
kolbyjack
  • 8,287
  • 2
  • 39
  • 31
1

Yup, that'd be the way to do it. If your patterns are going to stay that simple, you can probably combine them to reduce the volume of expression comparisons:

if ($http_user_agent ~ (iPhone|Android) ) {
    rewrite     ^(.*)   https://m.domain1.com$1 permanent;
}
if ($http_user_agent ~ (MSIE|Mozilla) ) {
    rewrite     ^(.*)   https://domain2.com$1 permanent;
}
Shane Madden
  • 116,404
  • 13
  • 187
  • 256