Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace request body in NGINX proxy for POST

Tags:

nginx

proxy

I'm trying to use NGINX to proxy a request that needs to do a bit of magic in the middle. Essentially I have a client that can only send an unauthenticated GET request, and I need to receive this request, make a POST that will login to a server using static credentials stored in the NGINX config, and replace the response body with an html redirect. This will work for my scenario because the POST response will contain a Set-Cookie header with a session id representing the authenticated session. I know I can use proxy_method to force NGINX to make the outbound call via POST, and I can use sub_filter to replace the POST response with the html redirect. My question is how can I set a request body that will get sent in the POST request?

Any ideas?

Ian

like image 621
IanG Avatar asked Mar 14 '23 18:03

IanG


1 Answers

Working example for Ubuntu 16.04 and Ubuntu 18.04

enter image description here

Installation

# sudo apt purge nginx-*  # maybe necessary, backup your /etc/nginx/… configs before!
sudo add-apt-repository ppa:nginx/stable
sudo apt-cache show nginx-extras | grep -E '(xenial|bionic)'
sudo apt install nginx-extras  # Lua support (nginx-extras is > nginx-full)

Config

/etc/nginx/sites-available/test.conf

server
{
    listen 80;
    server_name test.example.com;

    location /
    {
        if ($request_method = POST)
        {
            access_by_lua_block
            {
                ngx.req.read_body()
                local req = ngx.req.get_body_data()
                local newreq, n, err = ngx.re.gsub(req, "REPLACE", "REPLACED")
                ngx.req.set_body_data(newreq)
            }
        }

        include proxy_params;
        proxy_pass http://target.local:80/;
    }
}

Activate

cd /etc/nginx/sites-enabled
sudo ln -s ../sites-available/test.conf test.conf
sudo nginx -t
sudo service nginx reload  # or newer: sudo systemctl reload nginx

If there are no sites-available and sites-enabled folders, simply put test.conf in your conf.d folder.

like image 69
qräbnö Avatar answered Apr 01 '23 15:04

qräbnö