加载中...

Nginx if多条件判断


前言

Nginx默认是不支持直接进行多逻辑判断的,例如如下代码

        if ($http_user_agent != "curl" && $remote_addr != "172.16.182.204") {
                return 403;
        }

这样配置nginx -t会提示配置文件有错误

nginx: [emerg] invalid condition "$http_user_agent" in /usr/local/nginx/conf/conf.d/proxy.conf:38
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

所以需要采取其他的方案

使用变量实现与运算

        set $fooo " ";
        if ($http_user_agent != "curl" ) {
                set $fooo "${fooo}1";
        }

        if ($remote_addr != "172.16.182.204" ) {
                set $fooo "${fooo}1";
        }

        if ($fooo ~* "11") {
                return 403;
        }
        #当user_agent不等于curl且客户端地址不是172.16.182.204返回403

访问测试

curl -I -k -A "curl" https://172.30.151.219 #满足客户端地址不是172.16.182.204 但是user_agent是curl 所以正常返回
HTTP/1.1 200 OK
Date: Sun, 12 Jun 2022 06:27:05 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
Expires: Mon, 26 Jul 1997 05:00:00 GMT
curl -I -k  https://172.30.151.219  #user_agent不是curl 但是地址是172.16.182.204  正常返回
HTTP/1.1 200 OK
Date: Sun, 12 Jun 2022 06:31:42 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
Expires: Mon, 26 Jul 1997 05:00:00 GMT

curl -I -k  https://172.30.151.219  #两个条件都满足 返回403
HTTP/1.1 403 Forbidden
Date: Sun, 12 Jun 2022 06:31:10 GMT
Content-Type: text/html
Connection: keep-alive
Vary: Accept-Encoding

使用变量实现逻辑或运算

        set $fooo " ";
        if ($http_user_agent != "curl" ) {
                set $fooo 1;
        }

        if ($remote_addr != "172.16.182.204" ) {
                set $fooo 1;
        }

        if ($fooo ~* "1") {
                return 403;
        }

访问测试

curl -I -k  https://172.30.151.219  #user_agent不正确 
HTTP/1.1 403 Forbidden
Date: Sun, 12 Jun 2022 06:35:00 GMT
Content-Type: text/html
Connection: keep-alive
Vary: Accept-Encoding
curl -I -k -A "curl" https://172.30.151.219  #客户端ip地址不正确
HTTP/1.1 403 Forbidden
Date: Sun, 12 Jun 2022 06:35:45 GMT
Content-Type: text/html
Connection: keep-alive
Vary: Accept-Encoding
curl -I -k -A "curl" https://172.30.151.219   #两个都满足访问正常
HTTP/1.1 200 OK
Date: Sun, 12 Jun 2022 06:36:25 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
Expires: Mon, 26 Jul 1997 05:00:00 GMT

文章作者: huhuhahei
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 huhuhahei !
评论
  目录