How does Nginx proxy_pass pass a route parameter

Viewed 4203

I'm trying to make an api call to an internal docker container, but for every request url I have to make a proxy_pass in the Nginx config. I've read articles that the slashes at the end should work to pass all after de certain url to the proxy_pass.

Read here (redirect table)


Example

www.example.com/api -> redirects to correct endpoint

www.example.com/api/2020 -> this doesn't redirect to http://api/2020

Configuration

location = /api/ {
   proxy_pass http://api/;
}

So why doesn't this configuration pass the 2020 'parameter' to the api endpoint? It works when I make a configuration like this:

location = /api/2020 {
   proxy_pass http://api/2020;
}

But the problem is that it's a parameter so it can possibly be any number, how to solve this?

I've read other posts, but I ask this question again to get a broader understanding of the passing possibilities for parameters. Is it really necessary to use Regex for this?

3 Answers

Remove exact matching, just use

location /api/ {
   proxy_pass http://api/;
}

without any regexes.

You are using "=" regex for comparison so It will find same url so please read the below code & change your configuration.

 location ~ ^/(api)/ {
                proxy_pass http://api;
        }

After the above changes restart your nginx server & you dont need to write separate code for all the APIs.

I hope! It will resolve your problem.

This is very easy to solve:

location / {
   proxy_pass http://internal_addr:port$request_uri;   
}

Example for a IP/PORT: 172.168.1.1:3000, internal server:

location / {
   proxy_pass http://172.168.1.1:3000$request_uri;   
}

By doing this, everything that the external client requests to nginx after the / (routes, parameters, etc.) nginx will forward to the internal server in exactly the same way.


If you have more than one internal server, you can use something like this:

In server1(IP/PORT: 172.168.1.1:3333):

location /app1 {

proxy_pass http://172.168.1.1:3333$request_uri;
}

That is:

Client Request to Nginx: exemple.com/app1/login.php?x=y

Nginx Will send the request to server1 as /app1/login.php?x=y

In server2 (IP/PORT: 172.168.1.2:4444):

location /app2 {

proxy_pass http://172.168.1.2:4444$request_uri;
}

That is:

Client Request to Nginx: exemple.com/app2/login.php?x=y

Nginx Will send the request to server2 as /app2/login.php?x=y

Related