51

For example, I want to do this:

if ($http_user_agent ~ "MSIE 6.0" || $http_user_agent ~ "MSIE 7.0" (etc, etc)) {
    rewrite ^ ${ROOT_ROOT}ancient/ last;
   break;
}

instead of this:

if ($http_user_agent ~ "MSIE 6.0") {
    rewrite ^ ${ROOT_ROOT}ancient/ last;
   break;
}
if ($http_user_agent ~ "MSIE 7.0") {
    rewrite ^ ${ROOT_ROOT}ancient/ last;
   break;
}

Nginx rejects this syntax (minus the (etc, etc)), and I don't see anything in the docs about this.

Also, we opted not to use $ancient_browser directive, so that's not an option.

starball
  • 20,030
  • 7
  • 43
  • 238
Bryce Johnson
  • 6,689
  • 6
  • 40
  • 51

1 Answers1

75

Edit:

As Alexey Ten didn't add a new answer, I'll edit mine to give his better answer in this case.

if ($http_user_agent ~ "MSIE [67]\.")

Original answer:

Nginx doesn't allow multiple or nested if statements however you can do this :

set $test 0;
if ($http_user_agent ~ "MSIE 6\.0") {
  set $test 1;
}
if ($http_user_agent ~ "MSIE 7\.0") {
  set $test 1;
}
if ($test = 1) {
  rewrite ^ ${ROOT_ROOT}ancient/ last;
}   

It is not shorter but it allows you to do the check and put the rewrite rule only once.

Alternative answer:

In some cases, you can also use | (pipe)

if ($http_user_agent ~ "(MSIE 6\.0)|(MSIE 7\.0)") {
  rewrite ^ ${ROOT_ROOT}ancient/ last;
}  
Eric Ly
  • 2,095
  • 1
  • 20
  • 27
  • 7
    You can also use | (pipe) as an alternative like: if ($http_user_agent ~ "(MSIE 6.0)|(MSIE 7.0)") – dmonti Apr 23 '18 at 19:22
  • Note: as ~ does a regexp match, the '.' should be escaped as '\.' in all cases – Kutzi Feb 23 '21 at 09:45
  • You can also use the map with two variables, for example: https://serverfault.com/questions/760380/how-to-specify-several-variables-in-the-map-directive-of-nginx – fireman777 Apr 08 '21 at 10:48