nginx根據cookie分流
衆所周知,nginx能夠根據url path進行分流,卻不知對於cookie分流也很強大,同時這也是我上篇提到的小流量實驗的基礎。
二話不說,先看需求,兩臺服務器分別定義爲
apache001:192.168.1.1:8080
apache002:192.168.1.2:8080
默認服務器爲:
default:192.168.1.0:8080
前端nginx服務器監聽端口8080,須要根據cookie轉發,查詢的cookie的鍵(key)爲abcdexpid,若是該cookie值(value)以1結尾則轉發到apache001,以2結尾則轉發到apache002。
方案1:
用map,nginx.conf配置以下:前端
map $COOKIE_abcdexpid $group {
~*1$ apache001;
~*2$ apache002;
default root;
}
upstream apache001 {
server 192.168.1.1:8080 weight=1 max_fails=1 fail_timeout=30s;
}
upstream apache002 {
server 192.168.1.2:8080 weight=1 max_fails=1 fail_timeout=30s;
}
upstream root {
server 192.168.1.0:8080 weight=1 max_fails=1 fail_timeout=30s;
}
server {
listen 8080;
server_name neoremind.net;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "group=$group"'
'"$http_user_agent" $gzip_ratio $request_time "$http_x_forwarded_for"';
access_log logs/access_log main;
error_log logs/error_log;
location / {
proxy_pass http://$group;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
方案2:
利用set和if…else… ,nginx.conf配置以下:nginx
upstream apache001 {
server 192.168.1.1:8080 weight=1 max_fails=1 fail_timeout=30s;
}
upstream apache002 {
server 192.168.1.2:8080 weight=1 max_fails=1 fail_timeout=30s;
}
upstream root {
server 192.168.1.0:8080 weight=1 max_fails=1 fail_timeout=30s;
}
server {
listen 8080;
server_name beidoutest.baidu.com;
#match cookie
set $group "root";
if ($http_cookie ~* "abcdexpid=([^;]+)(1$)"){
set $group apache001;
}
if ($http_cookie ~* "abcdexpid=([^;]+)(2$)"){
set $group apache002;
}
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "group=$group"'
'"$http_user_agent" $gzip_ratio $request_time "$http_x_forwarded_for"';
access_log logs/access_log main;
error_log logs/error_log;
location / {
proxy_pass http://$group;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
map $COOKIE_id $group {
700003508 admin;
~*3$ admin;
default user;
}
upstream backend_user {
server 10.3.24.11:8080;
}
upstream backend_admin {
server 10.3.25.21:8081;
}
server {
listen 80;
server_name photo.domain.com;
location / {
proxy_pass http://backend_$group;
}
}
首先,是在nginx裏面配置一個映射,$COOKIE_id能夠解析出cookie裏面的id字段,$group是一個變量,{}裏面是映射規則,
這樣,若是一個id爲700003508的人來訪問,$group就等於admin。
而後在server裏面使用就會代理到http://backend_admin上apache
轉自:http://blog.csdn.net/yanook/article/details/8275716服務器