nginx 根据Header 重写方案

 

在多人(多服务)协作模式下,需要增加流量灰度路由能力。常见场景为:

C1  ---> S1

C2 ---> S1

C3 ----> S2

 

所以,可以通过 协议标注,识别路由流量。

可以实现

前端流量 根据Header 的不同路由到不同的后端服务,进而实现 开发与开发的解耦,开发与其他用户的解耦。

 

解决方案:

定义 http header name 为

X-KEY-TAG

由前端传递到后端Nginx

Nginx 根据header value 进行路由。

nginx 样例如下:

location /apiv2/ {

if ( $http_X-KEY-TAG = "km" ){

    proxy_pass http://xxx_normal.km:8080/api/v2/;

    break;

}

proxy_pass  http://xxx_normal.test:8080/api/v2/;

}

 

nginx 报错:

1. proxy_pass 不支持在 if statement 中以 /api/v2/结束。

* proxy_pass 仅支持在location 块内进行url重写

 

因此需要对url 进行rewrite 后再次进行 proxy_pass

方案调整为:

 

location /apiv2/ {

if ( $http_X-KEY-TAG = "km" ){

    rewrite /(.*)  /dev/km/$1 last; 

}

proxy_pass  http://xxx_normal.test:8080/api/v2/;

}

location /dev/km/apiv2/{

    proxy_pass http://xxx_normal.km:8080/api/v2/;

}

 

业务验证不通过。

通过增加log 发现$http_X-KEY-TAG  为空。

经过检索文档

需要在使用时$http_X_KEY_TAG 才行。

 

最终完整工作方案

location /apiv2/ {

if ( $http_X_KEY_TAG = "km" ){

    rewrite /(.*)  /dev/km/$1 last; 

}

proxy_pass  http://xxx_normal.test:8080/api/v2/;

}

location /dev/km/apiv2/{

    proxy_pass http://xxx_normal.km:8080/api/v2/;

}

 

posted @ 2022-08-23 19:26  风云力  阅读(370)  评论(0编辑  收藏  举报