nginx-location根据不同参数跳转

介绍

最近项目有个需求,需要根据不同的用户id跳转到后端不同接口,通过查看文档配置完成,特记录如下

配置

    server {
        listen       8093;
        server_name  localhost;
        access_log  logs/access_8093.log  main;
        location /test/get{
            proxy_redirect off;
            proxy_set_header  Host   $host:$server_port;
            proxy_set_header  X-Real-IP $http_x_forwarded_for;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        	# 定义一个变量为0
            set $is_matched 0;
            if ( $query_string ~* ^(.*)userId=(1000|1001|1002)(.*) ){
                # 当get参数中有 userId=(1000|1001|1002)(.*) 时设置变量为1
                set $is_matched 1;
                proxy_pass http://127.0.0.1:8194; 
            }
            # 当变量为0 是转发到 http://127.0.0.1:8193
            if ($is_matched = 0) {
                proxy_pass http://127.0.0.1:8193;
            }
        }
        error_page 400 404 413 /40x.html;
        location = /40x.html {
            return 200 "{error: 400 404 413}";
        }

        error_page   500 502 503 504  50x.html;
        location = /50x.html {
            return 200 "{error: 500 502 503 504}";
        }
    }