Nginx conditional proxy based on the contents of the request body

I am trying to configure the nginx proxy to another server only if the $ request_body variable matches a specific regular expression. But she does not work for me.

server{ listen 80 default; server_name www.applozic.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; if ($request_body ~* (.*)appId(.*)) { proxy_pass http://apps.applozic.com; } } 

}

request body:

  { "applicationId": "appId", "authenticationTypeId": 1, "enableEncryption": false, "notificationMode": 0, "deviceType": 4, } 
+7
proxy nginx
source share
2 answers

As far as I can tell, the problem is that the $request_body variable may not have been read in memory at the time your if statement was executed.

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

+1
source share
 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; } } 
+1
source share

All Articles