I am trying to run two express.js APIs in an EC2 instance with the help of PM2 and reverse-proxy using NGINX. Please find the NGINX config below,
NGINX config for the locations
My intention is to run the 2 APIs under the following routes:
/
to reverse proxy localhost:3000
/local
to reverse proxy localhost:3001
To make things more clear, I need the URL containing /local
or /local/
to proxy the API running on the port 3001
. However, when I try to hit https://example.com/local
or https://example.com/local/
, the response is received from the API running in port 3000 instead of the intended proxy.
This is the response returned when tried in the browser:
The solution needed is to successfully configure the 2 APIs to consume requests from the /
aka root domain and the /local
domain respectively. But both the requests go to the first one.
PS. I was also advised with a trick - tried switching the location positions (i.e. keeping the /local
location block first followed by the /
block) in the config file, still no luck - same behaviour.
The reverse proxy works fine redirecting the requests to the correct server, but the one running on '/local' gets requests forwarded containing '/local'. So the express app present there looks for /local in the route, but i figured out that was not configured. So have something like this.
app.get('/local', (req, res) => {
res.send('Hello World2!')
})
Just make sure to add the prefix '/local' for all the routes in the express app server at '/local' from nginx
And
"PS. I was also advised with a trick - tried switching the location positions (i.e. keeping the /local location block first followed by the / block) in the config file, still no luck - same behaviour."
The above will be the correct config because nginx will match and redirect the requests to the first applicable block. So if '/' stays before '/local' all the requests will be redirected to the first express app.