Correct proxy path in nginx.conf

2019-01-14 11:59发布

问题:

we have two servers, A and B. Server A is accessed worldwide. He has nginx installed. That's what I have in conf:

location /test {
  proxy_pass http://localserver.com;
}

What it should do, is translate the addreess http://globalserver.com/test (that is server A) to internal server address http://localserver.com. However, it does append the location path, that is, itries to look for http://localserver.com/test, which is not available at all. How can I make the proxy pass to the correct address, throwing out the last part in the location?

回答1:

That should work. Nginx should strip the '/test' path on the upstream local server. So what I can say is that is not the cause. To make it a bit better, try this:

location /test/ {
  proxy_pass http://localserver.com/;
}

The 2 slashes I added at the first 2 lines will avoid mistakenly match '/testABC' and send the wrong request to the upstream local server, for example.

Do you have a

proxy_redirect

line in the same location block? If your upstream local server has redirects, then a mistake on that line will cause an issue like you described.

[UPDATE] Found the root cause why the original config didn't work and mine works: nginx does NOT replace URI path part if the proxy_pass directive does not have a URI path itself. So my fix of adding a slash (slash is treated as a URI path) at the end triggers the URI path replacement.

Reference: http://wiki.nginx.org/HttpProxyModule#proxy_pass

If it is necessary to transmit URI in the unprocessed form then directive proxy_pass should be used without URI part

location  /some/path/ {
  proxy_pass   http://127.0.0.1;
}


回答2:

try to add as specified here http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass:

      proxy_pass http://localserver.com/;


回答3:

try rewrite

location /test {
    rewrite ^ $scheme://$host/;
    proxy_pass http://localserver.com;
}

some helpful links...

http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

http://wiki.nginx.org/Pitfalls



标签: nginx