Nginx高效分發之cookie篇

Nginx在做http代理轉發的角色時,我們可能有需要針對不同用戶請求的header,分佈到不同的上游upstream服務器組。這裏使用Cookie對用戶進行分類,然後配置Nginx實現上游服務器的分發。

業務場景:

一、 根據用戶所在城市分發,這裏使用了map模塊對匹配內容進行分發

1. upstream模塊配置:

upstream sh {

    server sh.domain.com;

}

upstream nj {

    server nj.domain.com;

}

upstream web {

    server web.domain.com;

}

2. map模塊配置:

map $cookie_user_city $upst {

    default web;

    ~sh sh;

    ~nj nj;

}

3. server模塊配置:

server {

    listen 80;

    server_name www.domain.com;

    location / {

        proxy_pass http://$upst;

    }

}

4. 訪問測試:

curl -i -b 'user_city=sh' http://www.domain.com

二、根據用戶請求ip進行分發,這裏使用了geo模塊對匹配內容進行分發

1. upstream模塊配置:

upstream test {

    server test.domain.com;

}

upstream nj_test {

    server nj.test.domain.com;

}

upstream sh_pro {

    server sh.domain.com;

}

2. geo模塊配置

geo $remote_addr $ip_list {

    192.168.0.0/24 test;

    10.0.0.0/8 test;

    172.16.0.0/16 test;

    211.156.181.25 nj_test;

}

3. server模塊配置:

server {

    listen 80;

    server_name www.domain.com;

    location / {

        if ($ip_list = 'test'){

        proxy_pass http://test;

        }

        if ($ip_list = 'nj_test'){

        proxy_pass http://nj_test;

        }

        proxy_pass http://sh_pro;

    }

}

這裏來簡單介紹一下map模塊和geo模塊。

map模塊是由ngx_http_map_module提供的,默認安裝,除非使用--without-http_map_module指令。map模塊可以創建變量進行關聯,可以整合多個不同的值到map模塊是由ngx_http_map_module提供的,默認安裝,除非使用--without-http_map_module指令。map模塊可以創建變量進行關聯,可以整合多個不同的值到一個或多個相同的值並存儲到變量當中,它維護的是一個映射關係。

geo模塊是由ngx_http_geo_module提供的,默認安裝,除非使用--without-http_geo_module。它是專門用來對IP進行分類的,可以將多個來源IP進行分組,用以實現讓不同來源的IP訪問不同的上游服務器。注意,geo模塊非geoip模塊。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章