I need to write an nginx location directive to proxy requests to subdirectory to another server preserving urlencoding and removing subdirectory prefix.
Here's an artificial example — request like this:
http://1.2.3.4/api/save/http%3A%2F%2Fexample.com
should pass as
http://abcd.com/save/http%3A%2F%2Fexample.com
I tried several different ways. Here're couple of them:
- From this SO question
location /api/ {
rewrite ^/api(/.*) $1 break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://abcd.com;
}
But it decodes the string, so http://abcd.com
gets /save/http://example.com
- From another SO question
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://abcd.com;
}
But it keeps subdirectory, so http://abcd.com
gets /api/save/http%3A%2F%2Fexample.com
.
What's needed is somewhere in the middle. Thank you!
UPD: Here's a ticket in nginx bug tracker
Challenge accepted!
That's it, folks!
Here's for the full proof.
The config file for
nginx/1.2.1
:Here are the results of running the queries for each location:
Note that having that extra
return 400;
is quite important — otherwise, you risk having a security issue (file access through//api
etc), as Maxim has briefly mentioned in your trac ticket.P.S. If you think using the rewrite engine as a finite-state automaton is super cool, you might also want check out my http://mdoc.su/ project, or fork it github.
What you have to do is fairly easy as long as we are talking prefix matching with
^~
or no modifierAnd everything will be passed along without decoding, you don't have to pass
$uri
Also while you use proxy pass you should also set these headers