How nginx builds the upstream path
If proxy_pass has no path after the host and port (http://127.0.0.1:3000), nginx forwards the original
URI as is. If anything follows the port — even a single / (http://127.0.0.1:3000/ or
http://127.0.0.1:3000/v2/) — nginx replaces the matched location prefix with that URI suffix
(Reverse proxy).
Before and after
# Request /api/users reaches the app as /api/users
location /api/ {
proxy_pass http://127.0.0.1:3000;
}
# Request /api/users reaches the app as /users (/api/ prefix stripped)
location /api/ {
proxy_pass http://127.0.0.1:3000/;
}
Exception: when proxy_pass contains a variable (proxy_pass $upstream;), automatic prefix replacement
turns off. Rewrite the path explicitly with rewrite ^/api/(.*)$ /$1 break; when you need it
(Docker).
If it doesn’t work
The app receives /users instead of /api/users and returns 404
- Cause
location /api/hasproxy_pass http://127.0.0.1:3000/;with a trailing slash, so nginx strips/api/.- Fix
- Drop the trailing slash:
proxy_pass http://127.0.0.1:3000;.
Double slashes //users show up in the backend log
- Cause
- Mismatched trailing slashes:
location /api(no/) withproxy_pass http://127.0.0.1:3000/;(with/). - Fix
- Put a trailing slash on both:
location /api/andproxy_pass http://127.0.0.1:3000/;.