Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite an Nginx GET request into POST?

My use case is that I have an email containing a "verify your email address" link. When the user clicks this link, the user agent performs a GET request like:

GET http://widgetwerkz.example.com/confirm_email?challenge=LSXGMRUQMEBO

The server will perform this operation as a POST (because it is a side-effecting operation). I do not have access to the server code at all. The destination request should be:

POST http://widgetwerkz.example.com/rpc/verify

{ "challenge": "LSXGMRUQMEBO" }

What Nginx rewrite can I perform to achieve this?

Edit: solution in context

http {
    server {
        # ... 
        location /confirm_email {
            set $temp $arg_challenge;
            proxy_method POST;
            proxy_set_body '{ "challenge": "$temp" }';
            proxy_pass http://127.0.0.1/rpc/verify;
            set $args '';
        }
    }
}

This does all these together:

  • Converts the request from GET to POST
  • Rewrites the location from /confirm_email to /rpc/verify
  • Removes the query string from the request (e.g. resulting url is simply /rpc/verify, without the ?challenge=LSXGMRUQMEBO)
  • Adds a JSON body of: { "challenge": "LSXGMRUQMEBO" }

Thanks to Ivan for putting me on the right track!

like image 766
Chris Avatar asked Dec 13 '18 16:12

Chris


People also ask

How do I create a rewrite rule in NGINX?

The syntax of rewrite directive is: rewrite regex replacement-url [flag]; regex: The PCRE based regular expression that will be used to match against incoming request URI. replacement-url: If the regular expression matches against the requested URI then the replacement string is used to change the requested URI.

What is return 301 in NGINX?

301 Permanent Redirection Permanent redirection will inform the browser that the website is no longer available with the old URL and this information should be updated and this point to the new URL we published.


1 Answers

You need something like this:

location /confirm_email {
    proxy_method POST;
    proxy_set_body '{ "challenge": "$arg_challenge" }';
    # your proxy_set_headers and other parameters here
    proxy_pass <your_backend>/rpc/verify?;
}
like image 82
Ivan Shatsky Avatar answered Nov 01 '22 13:11

Ivan Shatsky