Sub topic 4
How proxy_pass rewrites the request URI
This chapter explains how proxy_pass decides which path the backend receives. It covers the two forms of proxy_pass, how location prefixes interact with each form, the cases where Nginx cannot rewrite at all, and how to check the result.
Prerequisites
This chapter assumes you already know:
- How an Nginx
serverblock andlocationblock are structured, and how to runnginx -tand reload. - How
locationmatching picks a block (prefix, exact, regex). - What a request line looks like:
GET /api/users?id=7 HTTP/1.1.
Many "my backend returns 404 only through Nginx" problems come from this chapter's topic. The cause is usually a stray or missing slash.
The core rule
When Nginx forwards a request, it builds a new request line for the backend. It makes one of two choices about the path.
proxy_passhas no URI part. Nginx forwards the original request URI unchanged.proxy_passhas a URI part. Nginx replaces the part of the request path that matched thelocationprefix with that URI.
A URI part is anything after the host and port. A single / counts. This is the key detail:
| `proxy_pass` value | Has URI part? |
|---|---|
| `http://127.0.0.1:3000` | No |
| `http://127.0.0.1:3000/` | Yes (`/`) |
| `http://127.0.0.1:3000/app/` | Yes (`/app/`) |
| `http://127.0.0.1:3000/app` | Yes (`/app`) |
A trailing slash on the address is not cosmetic. It switches Nginx from "pass the path as received" to "substitute the matched prefix".
Form 1: no URI part
With no URI part, the backend sees the same path the client sent, including the query string.
location /api/ {
proxy_pass http://127.0.0.1:3000;
}| Client requests | Backend receives |
|---|---|
| `/api/users` | `/api/users` |
| `/api/users?id=7` | `/api/users?id=7` |
| `/api/` | `/api/` |
Use this form when the backend already serves its routes under the same prefix, such as an application that expects /api/....
Form 2: with a URI part
With a URI part, Nginx takes the request path and swaps the text that matched the location prefix for the proxy_pass URI. The rest of the path and the query string are kept.
location /api/ {
proxy_pass http://127.0.0.1:3000/;
}Here the location prefix is /api/ and the replacement is /.
| Client requests | Matched prefix | Backend receives |
|---|---|---|
| `/api/users` | `/api/` | `/users` |
| `/api/users?id=7` | `/api/` | `/users?id=7` |
| `/api/` | `/api/` | `/` |
Use this form to strip a prefix. The backend can serve routes at its root while the public site exposes them under /api/.
You can also swap one prefix for another:
location /api/ {
proxy_pass http://127.0.0.1:3000/v2/;
}A request for /api/users now reaches the backend as /v2/users.
The diagram below shows the decision.
The slash-matching trap
Because the substitution is a plain text replacement, the slashes on both sides must line up. Consider a mismatch:
location /api {
proxy_pass http://127.0.0.1:3000/;
}The prefix /api has no trailing slash, but the replacement / does. For the request /api/users, Nginx removes /api and puts / in its place. The remaining text is /users, so the result is //users, with a double slash. Some backends tolerate that. Many return 404.
The same problem appears in reverse:
location /api/ {
proxy_pass http://127.0.0.1:3000/v2;
}For /api/users, Nginx removes /api/ and puts /v2 in its place. The result is /v2users, which is almost never what you want.
| `location` | `proxy_pass` URI | Request | Backend receives |
|---|---|---|---|
| `/api/` | `/` | `/api/users` | `/users` |
| `/api` | `/` | `/api/users` | `//users` |
| `/api/` | `/v2` | `/api/users` | `/v2users` |
| `/api` | `/v2` | `/api/users` | `/v2/users` |
| `/api/` | `/v2/` | `/api/users` | `/v2/users` |
The safe habit is to end both the location prefix and the proxy_pass URI with a slash, or to omit the URI part entirely.
Requests that equal the prefix without a trailing slash
If you use location /api/, a request for exactly /api does not match that block. Nginx sees the prefix location /api/ and sends a 301 redirect from /api to /api/. This works only when the location is a plain prefix handled by proxy_pass. That redirect is built into the matching logic. It does not appear when you use location = /api or a regex location.
Cases where Nginx cannot substitute the prefix
Nginx can only replace "the matched prefix" when there is a prefix to replace. In three situations it does not apply the URI part. In each, the proxy_pass directive behaves as if the URI were passed unchanged, and in some cases it refuses to load.
Regex locations
In a regex location (~ or ~*), there is no fixed prefix. Nginx rejects a proxy_pass that has a URI part inside a regex location:
location ~ ^/api/ {
proxy_pass http://127.0.0.1:3000/;
}Running nginx -t on this fails with an error similar to:
nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" blockThe same error applies to named locations (@name), if blocks, and limit_except blocks. In those places, write proxy_pass with no URI part, and change the path with rewrite if you need to.
After a rewrite in the same location
If a rewrite ... break; changes the URI inside the location, Nginx forwards the rewritten URI as it now stands. Any URI part on proxy_pass is ignored.
location /legacy/ {
rewrite ^/legacy/(.*)$ /v1/$1 break;
proxy_pass http://127.0.0.1:3000;
}A request for /legacy/items reaches the backend as /v1/items. Here proxy_pass has no URI part, which matches the intent. If it had one, Nginx would still send the rewritten URI.
Using a rewrite is the standard way to handle regex locations:
location ~ ^/api/v(\d+)/(.*)$ {
rewrite ^/api/v\d+/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:3000;
}Variables in proxy_pass
If proxy_pass contains a variable, Nginx treats the whole value as the final URI target. It does not substitute a matched prefix.
location /api/ {
set $backend http://127.0.0.1:3000;
proxy_pass $backend;
}When the variable holds only a scheme, host and port, Nginx sends the original request URI. If you want a prefix stripped, put the new path in the variable yourself, or use a rewrite:
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
set $backend http://127.0.0.1:3000;
proxy_pass $backend;
}There is a second consequence of variables. Nginx resolves a hostname written directly in proxy_pass once, when it loads the configuration. When the target is a variable, Nginx resolves the name at request time and needs a resolver directive for any hostname that is not an IP address or a defined upstream group.
Encoded characters and normalization
Nginx normalizes the path before matching. It decodes percent-encoded characters, collapses duplicate slashes (when merge_slashes on, the default) and resolves . and .. segments. When proxy_pass has no URI part, Nginx forwards the original, unprocessed request URI. When it has a URI part, the forwarded path is built from the normalized one.
This can matter when the backend treats %2F or a double slash as significant. If the backend needs the exact bytes the client sent, use proxy_pass with no URI part. Pairing proxy_pass http://backend; with a matching backend route is the most predictable choice.
The query string
Both forms keep the query string. In form 2, Nginx replaces only the path portion, so /api/users?id=7 becomes /users?id=7. The rewrite directive also appends the original arguments unless the replacement ends with ?.
Verifying the result
Do not guess what the backend receives. Log it. The $request_uri variable holds the original URI as the client sent it, and $uri holds the current normalized URI. To see the path sent upstream, run a small test backend that prints the request line.
from http.server import BaseHTTPRequestHandler, HTTPServer
class Echo(BaseHTTPRequestHandler):
def do_GET(self):
body = f"path={self.path}\n".encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 3000), Echo).serve_forever()Save it as echo.py and run python3 echo.py. Then configure Nginx and test:
sudo nginx -t && sudo systemctl reload nginx
curl -s "http://example.com/api/users?id=7"The response shows path=/users?id=7 or path=/api/users?id=7, depending on the form you chose. The echo server prints the exact path Nginx sent.
Choosing between the forms
| Goal | Configuration |
|---|---|
| Backend serves routes under the same prefix | `location /api/ { proxy_pass http://host:port; }` |
| Backend serves routes at its root, public path has a prefix | `location /api/ { proxy_pass http://host:port/; }` |
| Public prefix maps to a different backend prefix | `location /api/ { proxy_pass http://host:port/v2/; }` |
| Regex-based mapping | `rewrite ... break;` plus `proxy_pass` with no URI part |
| Backend needs the raw, unnormalized URI | `proxy_pass` with no URI part |
The same rules apply when proxy_pass points to an upstream group. The group name takes the place of the host and port. proxy_pass http://app_backend; passes the URI unchanged, and proxy_pass http://app_backend/; strips the matched prefix.
Common errors
- Backend returns 404 only through Nginx. Compare the path in the backend's log with the path you intended. A missing or extra slash is the most common cause.
- Double slashes in backend logs. The
locationprefix lacks a trailing slash andproxy_passends in/. nginx -treports "cannot have URI part".proxy_passhas a URI part inside a regex, named,iforlimit_exceptcontext. Remove the URI part and userewrite.- Prefix is not stripped when a variable is used. Variables disable prefix substitution. Use
rewriteor build the path in the variable. - Redirects from the backend point at the wrong path. The backend does not know about the public prefix. Look at
proxy_redirect, which rewritesLocationheaders. That directive has its own defaults and is outside this chapter.
Exercise
A site uses location /shop/ { proxy_pass http://127.0.0.1:4000/store/; }. What path does the backend receive for the client request /shop/items/9?color=red? What would it receive if the proxy_pass line were proxy_pass http://127.0.0.1:4000;?
Show answer
With the URI part /store/, Nginx replaces the matched prefix /shop/ with /store/, so the backend receives /store/items/9?color=red. Without a URI part, Nginx forwards the original URI, so the backend receives /shop/items/9?color=red.
Exercise
A configuration has location /api { proxy_pass http://127.0.0.1:3000/; } and the backend logs show requests for //users. Explain why, and give two different fixes.
Show answer
The location prefix /api has no trailing slash, so for /api/users Nginx removes /api and inserts /, leaving /users appended to /, which gives //users. One fix is to change the location to /api/ so both ends use a slash. Another is to remove the URI part from proxy_pass (use http://127.0.0.1:3000) if the backend serves routes under /api.
Exercise
You need to map /api/v2/orders to /orders on the backend with a regex location. Why does location ~ ^/api/v\d+/ { proxy_pass http://127.0.0.1:3000/; } fail, and what is a working configuration?
Show answer
Nginx does not allow a URI part in proxy_pass inside a regex location, so nginx -t reports an [emerg] error. A working configuration uses a rewrite: location ~ ^/api/v\d+/ { rewrite ^/api/v\d+/(.*)$ /$1 break; proxy_pass http://127.0.0.1:3000; }.