nginx實現根據cookie分流


0.環境:centos7.2,tomcat8.5*2 ,nginx1.0.13

0-1:起因,由於上線不能影響用戶使用,起初使用ip分流,但是有些情況無法獲取ip,故查到可以用cookie做分流,這樣一來,可以給客戶以及測試人員分配角色 ,根據角色設置cookie,再根據cookie實現分流,便可實現上線不影響現網使用。

1.nginx配置

      upstream nttest{
        #       server 127.0.0.1:38080;
                server 127.0.0.1:39090;

        }
        upstream nttest1{
                server 127.0.0.1:38080;
        }
 location ^~ /web/ {
             set $group nttest;
              if ($http_cookie ~* "hyb_test") {
                         set $group nttest1;
              }
             proxy_redirect              off;
             proxy_set_header            Host $host;
             proxy_set_header            X-real-ip $remote_addr;
             proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
             index index.html index.htm;
             proxy_pass http://$group;
 }

即,聲明2個upstream,分別指向tomcat1和2,當路徑匹配到web,設置變量group為nttest節點,判斷cookie,如果cookie帶有hyb_test,則設置變量group為nttest1節點,將請求代理到group。

2測試用例准備

 
index.jsp
 @RequestMapping("/login") public String login2(String username,String password, HttpServletRequest req, HttpServletResponse resp){ if("hyb".equals(username)){ Cookie cookie = new Cookie("hyb_test_username",username); cookie.setPath("/"); // cookie.setDomain("domain"); resp.addCookie(cookie); } return "success"; } 
 
跳轉頁面

 

將項目拉到2個tomcat,修改2.jsp內容即可,比如我將nttest1下的2.jsp修改為
 
image.png

3測試分流

分別啟動tomcat1,tomcat2,正常啟動后訪問index.jsp


 
index

因為沒做登陸校驗,直接點登陸即可,另開一個窗口,用hyb做用戶名登陸,如圖


 
image.png

分別點擊登陸,
 
image.png

hyb已經成功訪問到nttest1,而其他登陸則訪問了nttest,分流成功!

 

再看cookie
 
image.png
 
image.png


作者:hybzzz
鏈接:https://www.jianshu.com/p/b8fa8adb5119
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM