Note that URL decoding, commonly known as $uri
"normalisation" within the documentation of nginx, happens before the backend IFF:
either any URI is specified within proxy_pass
itself, even if just the trailing slash all by itself,
or, URI is changed during the processing, e.g., through rewrite
.
Both conditions are explicitly documented at http://nginx.org/r/proxy_pass (emphasis mine):
If the proxy_pass
directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive
If proxy_pass
is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI
The solution depends on whether or not you need to change the URL between the front-end and the backend.
If no URI change is required:
# map `/foo` to `/foo`:
location /foo {
proxy_pass http://localhost:8080; # no URI -- not even just a slash
}
Otherwise, if you do need to swap or map /api
of the front-end with /app
on the backend, then you can get the original URI from the $request_uri
variable, and the use the rewrite
directives over the $uri
variable similar to a DFA (BTW, if you want more rewrite
DFA action, take a look at mdoc.su). Note that the return 400
part is needed in case someone tries to get around your second rewrite rule, as it wouldn't match something like //api/
.
# map `/api` to `/app`:
location /foo {
rewrite ^ $request_uri; # get original URI
rewrite ^/api(/.*) /app$1 break; # drop /api, put /app
return 400; # if the second rewrite won't match
proxy_pass http://localhost:8080$uri;
}
If you simply want to add a prefix for the backend, then you can just use the $request_uri
variable right away:
# add `/webapp` to the backend:
location / {
proxy_pass http://localhost:8080/webapp$request_uri;
}
You might also want to take a look at a related answer, which shows some test-runs of the code similar to the above.