NGINX支持if的 and 与 or 或者 && 与 || 吗?

本文介绍了如何在Nginx中正确使用条件判断实现AND及OR逻辑,通过具体实例展示了如何设置变量并进行条件检查,避免配置错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

答案是No.
当你尝试这样配置, 重载nginx时, 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;
    }

转载于:https://my.oschina.net/yonghan/blog/750861

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值