[nginx] 代理转发和地址替换

需求

客户端请求的nginx代理地址:

http://192.168.1.50:3000/dev/xxx

实际需要根据Header中 use_bff 的状态,如果值为 1 则转发到 bff 服务

http://192.168.1.60:3003/xxx

否则转发到默认服务

http://192.168.1.70:8000/v100/xxx

配置 nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    keepalive_timeout  65;
  
    # 默认服务
    upstream mysvr {
        server 192.168.1.70:8000;
    }

    # bff 服务
    upstream bff-svr {
        server 192.168.1.60:3003;
    }

    server {
        listen  3000;
        server_name  192.168.1.50;


        location /dev {
            add_header Access-Control-Allow-Headers 'X-Requested-With,Origin,Host,Content-Type,Accept,esn,token,AppUserToken,appid,tenantid,tagid,use_bff';
	
            # 根据 header 转发到 bff
            if ($http_use_bff) {
	            rewrite	"^\/dev+[a-z]*\/(.*)$" /$1 break;
                proxy_pass	http://bff-dev;
                break;
            }

            # 默认流量
            rewrite	"\/dev\/(.*)$" /v100/$1 break;
            proxy_pass    http://mysvr;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
}


posted @ 2021-05-06 14:43  我爱我家喵喵  阅读(3034)  评论(0编辑  收藏  举报