nginx通过header的值分流后端

背景:公司业务要求,需要获取前端header的值,根据不同的值分流到不同的后盾服务器,经多次测试,以下方法实现效果:

server {  
        listen 80;  
        charset utf-8;  
        underscores_in_headers on;  
        location / {  
            root    html;  
            index index.html index.htm;   
            if ($http_hospitalId = "9090") {  
                proxy_pass http://127.0.0.1:8080; 
            } 
            if ($http_hospitalId = "30000") {  
                proxy_pass http://192.168.53.10:8080; 
            }  
        }  
    } 

“ = ” 等于

“ != ” 不等于

PS:要点: 在if里做proxy_pass, 只能纯域名, 不能有任何uri成份,否则语法检测报错 ;
underscores_in_headers on:nginx是支持读取非nginx标准的用户自定义header的,但是需要在http或者server下开启header的下划线支持,比如自定义header为hospitalId,获取该header时需要这样:$http_hospitalId(一律采用小写,而且前面多了个http_)

 

posted @ 2021-07-19 11:05  太阳的阳ฅ  阅读(304)  评论(0编辑  收藏  举报