我怎样才能重写这个 nginx "if" 声明?
How can I rewrite this nginx "if" statement?
例如,我想这样做:
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 指令,所以这不是一个选项。
编辑:
由于 Alexey Ten 没有添加新答案,我将编辑我的答案以在这种情况下给出他更好的答案。
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;
}
例如,我想这样做:
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 指令,所以这不是一个选项。
编辑:
由于 Alexey Ten 没有添加新答案,我将编辑我的答案以在这种情况下给出他更好的答案。
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;
}