Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

How can I use an "or" operator in an nginx "if" statement?

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. Thanks in advance.

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

question from:https://stackoverflow.com/questions/29756330/how-can-i-use-an-or-operator-in-an-nginx-if-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...