nginx中只有if关键字,并不支持else语法,if的使用方法为:

if ($xxx = xxx) {
    xxx
}

和代码不同的是:if条件语句判断相等时只要一个等号,不能是==

虽然不支持else,但是可以使用以下的方法来模拟实现else:

server {
    server_name *.maqian.io;
    listen 80;
    
    location / {
        set $is_matched 0;
        if ($host = a.maqian.io) {
            proxy_pass http://127.0.0.1:1001/;
            set $is_matched 1;
        }
        
        if ($host = b.maqian.io) {
            proxy_pass http://127.0.0.1:1002/;
            set $is_matched 1;
        }
        # 没有匹配到,跳转到默认页面
        if ($is_matched = 0) {
            proxy_pass http://127.0.0.1;
        }
        
        # xxx
        # xxx
        # xxx
    }
}
最后修改:2018 年 12 月 16 日
如果觉得我的文章对你有用,请随意赞赏