Reverse Proxy to Multiple Endpoints using NGINX

If you are a NodeJS developer, you know that you can easily create multiple Nodes and each of them can have their own ports to connect to.

For example, you might want to display the FrontEnd of the app via http://localhost:8080 and the API via http://localhost:3000

Now, in order to use a single domain to access this, I can use the location block within NGINX configuration and let NGINX forward the request to multiple endpoints depending on the conditions.

Here are the sample server blocks:

server {
location / {
proxy_pass <a href="http://localhost:8080">http://localhost:8080</a>;
}

location /api {
rewrite ^/api(.*) /$1 break;
proxy_pass <a href="http://localhost:3000">http://localhost:3000</a>;
    }
}

Here the first location block directly forwards the request to http://localhost:8080.

However, for us, the requirement was to make use of API calls as well.

So here the requests like https://www.mydomain.com/apifind/x would simply get forwarded to

http://localhost/find/x. This means, now if I can use the same domain and route the requests to different servers depending on the needs.

 

Happy Coding!