nginx conditional proxy pass based on request body content

前端 未结 2 1093
再見小時候
再見小時候 2021-02-19 17:08

I am trying to configure nginx to proxy pass the request to another server, only if the $request_body variable matches on a specific regular expression.But it is not working for

相关标签:
2条回答
  • 2021-02-19 17:48

    I found the solution.

    I did following changes in nginx(open resty) config file

    upstream algoapp {
       server 127.0.0.0.1:543;
    }
    upstream main {
       server 127.0.0.1:443;
    }
    
    location /rest/ws/login {
       proxy_set_header X-Forwarded-Host $host;
       proxy_set_header X-Forwarded-Server $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Url-Scheme $scheme;
       proxy_set_header X-Forwarded-Proto $scheme;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       if ($request_method = OPTIONS ) {
       proxy_pass https://127.0.0.1:543;
       }
       if ($request_method = POST ) {
       set $upstream '';
       access_by_lua '
       ngx.req.read_body()
       local data = ngx.req.get_body_data()
       local  match = ngx.re.match(ngx.var.request_body, "appId")
       if match then
          ngx.var.upstream = "algoapp"
       else
       ngx.var.upstream = "main"
       end
       ';
       proxy_pass https://$upstream;
       }
    }
    
    0 讨论(0)
  • 2021-02-19 18:03

    As best I can tell the issue is that the variable $request_body may not have been read into memory at the time your if statement is executing.

    Suggested alternatives would be to use the lua support or compile nginx with the echo modules and run echo_request_body.

    0 讨论(0)
提交回复
热议问题