I have been using openresty nginx for simple request forwarding purpose, it is working as expected, i am forwarding each incoming request to another URL using below code :
location /app/ {
proxy_pass https://example.com/abc/;
proxy_read_timeout 60s;
proxy_pass_header Server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-Frame-Options "SAMEORIGIN" always;
and i am logging each POST request with below code :
server {
log_format post_logs '[$time_local] "$request" $status '
'$body_bytes_sent "$http_referer" '
'"$http_user_agent" [$request_body]';
}
location /app/ {
access_log logs/post.log post_logs;
}
Now my requirement is that before forwarding each request, i want to filter post request body data for specific string/keyword , it should only forwarded to proxy URL https://example.com/abc/ if specific string/keyword is found in post data.
I did some research but did not find anything that helps me achieve this, can anyone help ?
Finally I got it done with help of lua :
location /app/ {
.
.
.
access_by_lua '
ngx.req.read_body()
local data = ngx.req.get_body_data()
local match = ngx.re.match(ngx.var.request_body, "<reqid>search</reqid>")
#local match = ngx.re.match(ngx.var.request_body, "<reqid>search</reqid>","i") for case insensitive match
if match then
#nothing to do
else
return ngx.exit(ngx.HTTP_FORBIDDEN)
end';
proxy_pass https://example.com/abc/;
}
here request body data will be assign to variable 'data' and with use of ngx.re.match we can match string/keyword with request body data, in above example if <reqid>search</reqid>
not found in request body then it will return 403 forbidden, if found then it will be passed to proxy_pass.
It can be very useful for filtering incoming request before processing it.