【问题标题】:How can I rewrite this nginx "if" statement?如何在 nginx“if”语句中使用“or”运算符?
【发布时间】:2015-06-27 16:14:51
【问题描述】:

例如,我想这样做:

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

而不是这个:

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 拒绝这种语法(减去 (etc, etc)),我在文档中没有看到任何关于此的内容。提前致谢。

另外,我们选择不使用 $ancient_browser 指令,所以这不是一个选项。

【问题讨论】:

  • 在这种情况下,它就像if ($http_user_agent ~ "MSIE [67]\.") 一样简单。你忘了它是正则表达式。
  • @AlexeyTen 你应该写一个答案——IMO 它比提供的其他解决方案更可取。

标签: nginx


【解决方案1】:

编辑:

由于阿列克谢十没有添加新答案,我将编辑我的答案,以便在这种情况下给他更好的答案。

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

原答案:

Nginx 不允许多个或嵌套的 if 语句,但是你可以这样做:

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

它并不短,但它允许您进行检查并只放置一次重写规则。

替代答案:

在某些情况下,您还可以使用 | (管道)

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

【讨论】:

  • 你也可以使用 | (pipe) 作为替代方案,例如: if ($http_user_agent ~ "(MSIE 6.0)|(MSIE 7.0)")
  • 注意:正如 ~ 做一个正则表达式匹配,'.'应该转义为 '\.'在所有情况下
  • 您也可以使用带有两个变量的地图,例如:serverfault.com/questions/760380/…
猜你喜欢
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
  • 2017-12-04
  • 2021-06-20
  • 2011-01-10
相关资源
最近更新 更多