nginx中如何实现if/else

itlao6 工具&方法评论561字数 600阅读2分0秒阅读模式

一直都知道nginx支持if语法,而且语法和平常的开发语言代码格式差不多:

# 需要注意的是:if条件判断语句是用一个等号进行相等判断
if ($flag = '1') {
    return 404;
}

 文章源自IT老刘-https://itlao6.com/9938.html

然而,今天需要在nginx中设置if/elseif条件过滤,却发现不支持else;
最后在网上找到到如下解决方案:文章源自IT老刘-https://itlao6.com/9938.html

server {
    server_name itlao5.com;
    listen 80;
    
    location / {
        set $flag 0;
        if ($host = v.itlao5.com) {
            set $flag 1;
        }
        
        if ($host = f.itlao5.com) {
            set $flag 2;
        }
    
        if ($flag = 0) {
      # 没有匹配到,跳转到默认页面
            proxy_pass https://127.0.0.1:8000;
        }
        if ($flag = 1) {
      # 匹配到条件1,跳转到8001端口
            proxy_pass https://127.0.0.1:8001;
        }
    if ($flag = 2) {
      # 匹配到条件2,跳转到8002端口
            proxy_pass https://127.0.0.1:8002;
        }
    }
}

以上代码等效于:文章源自IT老刘-https://itlao6.com/9938.html

if(host == v.itlao5.com) {
  跳转https://127.0.0.1:8001
} else if(host == f.itlao5.com) {
  跳转https://127.0.0.1:8002
} else {
  跳转https://127.0.0.1:8000
}

 文章源自IT老刘-https://itlao6.com/9938.html 文章源自IT老刘-https://itlao6.com/9938.html

weinxin
我的微信公众号
微信扫一扫关注公众号,不定时更新
itlao6
  • 本文由 发表于 2022年 12月 6日 12:54:57
  • 转载请务必保留本文链接:https://itlao6.com/9938.html
评论  0  访客  0
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定