nginx根据cookie实现重定向式灰度(AB)发布需求

 大家知道,一般情况下,灰度(AB)发布需求设置nginx都只到/,但如果有

/xxx要重定向到/yyy/xxx呢,这种我们知道用 rewrite,但是注意rewrite后面一定要跟break,官方文档解释如下:

  • When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):
  • location /name/ {
        rewrite    /name/([^/]+) /users?name=$1 break;
        proxy_pass http://127.0.0.1;
    }

所以我们参考这个,给出了如下重定向式灰度(AB)发布需求的代码,仅供参考:

原理是:根据不同的cookie值跳转到不同组的机器,我们采用cookie关联upstream方式实现。其中upstream配置如下:

upstream  stg-hhplus-default-back-platform-web{

 server 192.168.1.1:8080;

}

upstream  stg-hhplus-test-back-platform-web{

 server 192.168.1.2:8080;

}

cookie abc=test时,将走灰度组,其他情况走default组。上面这段配置套路比较固定,如果你有发布系统,可以使用发布系统在发布灰度时生成。

(注:如果在测试时想在一进入主站即开启灰度,可以在发任意POOL时,将其他POOL也设置一个灰度UPSTREAM,不过内容和DEFAULT UPSTREAM一样,这样访问时非灰度项目访问的是DEFAULT机器,而灰度项目走灰度机器,方便测试。

如果遇多次发布灰度组,可能组名不同,那每次都生成一个新的灰度UPSTREAM就好了,或者已经存在的就覆盖内容,再三强调,内容和DEFAULT UPSTREAM一样。那么,久而久之,UPSTREAM是不是过多,再做一个清理的功能,让操作人员自行清理

历史UPSTREAM)

配置参考:

第一步,先在 server{

 ...

}

中增加如下配置,其中abc为你的cookie id

set $group $cookie_abc;
if ($group = ""){
	set $group "default";
}

第二步,在你要重写的location段中,如plugins段,按如下规则编写

location /plugins{
   #此处如果你还有变量需要增加,比如扩充$group,记得要在rewrite语句之前写,否则无效。如下所示
   set $last_cookie "stg-hhplus-$group-back-platform-web";
    rewrite /(.*) /back-platform-web/$1 break;
    proxy_pass http://$last_cookie;
    proxy_set_header Host $host:80;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For  $remote_addr;
    break;
}

猜你喜欢

转载自jdkleo.iteye.com/blog/2398290