Search code examples
nginxnginx-reverse-proxy

NGINX: How to add query string in a reverse proxy?


I am trying to set up a reverse proxy for requesting rest api, let's say for instance that i am making a request like this:

127.0.0.1/v1/resources/get/list/23948

The expected request on target host should be like this:

http://api.example.com/v1/resources/get/list/23948?key=skdma239mfmd0idfm9844

You can see in the expected request there is a query string, the reason for this is to protect the values from the client so the sensitive data is not leaked.

I have tried location definitions like this:

location /v1/resources/get/ {
    proxy_pass http://api.example.com$uri?key=sdkmfg234msdkmad9898
}

but for some reason NGINX responds with 500.

Is it possible to add query strings in a proxy_pass? or is it possible to add the query string to the reverse proxy so this data is protected?

NOTE: i know there is a question in stackoverflow that looks similar to this one, but none of the answers in that question helps with my problem. I have edited the code on how i attempted it last time and nginx responds 502 status


Solution

  • After some deep reading on nginx documentation and with the help of @RichardSmith i was able to successfully make the request with proxy_pass using resolver.

    The problem is that when using proxy_pass with a domain, the built-in resolver of nginx will try to resolve by itself to see if the DNS is cached, since there was no DNS resolver defined, nginx fails to complete the request.

    my location definition ended up like this:

    location /v1/resources/get/ {
        resolver 8.8.8.8;
        proxy_pass http://api.example.com$uri?key=sdkmfg234msdkmad9898
    }
    

    since this was for the sake of testing, i used google's default resolver which is 8.8.8.8