Question

How to make Nginx redirect a request to only one location?

I have a reverse proxy for two locations / and /services

server {
...

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /services {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

...
}

And there are two NodeJS APIs one is listening on port 3000 and the other on 3001. Whenever I send a request to example.com/services it gets handled by both apps. I want it to get handled only by the second app listening on port 3001. How do I achieve that?


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

This article explains location matching well:

https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms

But “location /” will always be matched first because /services isn’t an actual file on the server.

Cheers