How to rewrite an Nginx GET request into POST?
Asked Answered
S

1

6

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!

Suzettesuzi answered 13/12, 2018 at 16:13 Comment(2)
Does your nginx acts as a reverse-proxy server to your backend?Menorrhagia
Yes, Nginx is a local reverse proxy.Suzettesuzi
M
7

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?;
}
Menorrhagia answered 13/12, 2018 at 17:8 Comment(3)
This almost works, but the query parameter is still part of the request: POST http://widgetwerkz.example.com/rpc/verify?challenge= LSXGMRUQMEBO and that is causing problems for the backend.Suzettesuzi
Try to add a question sign after /rpc/verify, this might help. If not, write a comment, I'll search another way to get rid of it.Menorrhagia
That did it, Thanks!Suzettesuzi

© 2022 - 2024 — McMap. All rights reserved.