Nginx IF逻辑运算的实现方法
在前文《Nginx if语句加正则表达式实现字符串截断》中,我们探讨了利用if指令进行字符串截取的方法。本文将进一步讲解if指令在逻辑判断方面的应用技巧。所谓逻辑用法,即指程序中常见的与(and)和或(or)关系处理。
NGINX支持if的 and 与 or 或者 && 与 || 吗?
答案是不支持。当尝试在配置文件中直接编写如下代码并执行重载时,Nginx会报错。 复制代码 代码如下: location = /test/ { default_type text/html; set $b 0; if ( $remote_addr != '' && $http_x_forwarded_for != '' ){ set $b '1'; } echo $b; } [root@test-vm ~]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] invalid condition "$remote_addr" in /usr/local/nginx/conf/nginx.conf:60 configuration file /usr/local/nginx/conf/nginx.conf test failed 那么我们应该怎样来实现and 和or的逻辑关系呢? 复制代码 代码如下: location = /test_and/ { default_type text/html; set $a 0; set $b 0; if ( $remote_addr != '' ){ set $a 1; } if ( $http_x_forwarded_for != '' ){ set $a 1$a; } if ( $a = 11 ){ set $b 1; } echo $b; } location = /test_or/ { default_type text/html; set $a 0; set $b 0; if ( $remote_addr != '' ){ set $a 1; } if ( $http_x_forwarded_for != '' ){ set $a 1; } if ( $a = 1 ){ set $b 1; } echo $b; }