With nginx proxy/rewrite can I keep the original U

2019-08-07 08:38发布

问题:

Using nginx.conf features like proxy-pass/rewrite, can I keep the original URL in the browser's Location field?

I have several PlayFramework apps running on different ports (9001, 9002, ...) with proxy forwarding set up via nginx.conf. People browse to them as:

  • http://domain.name/App1/
  • http://domain.name/App2/
  • etc.

My nginx.conf entries look like this:

location /App1/ {
    proxy_pass http://localhost:9001/;
    rewrite ^/App1/(.*) http://domain.name:9001/$1;
}

If I ask for http://domain.name/App1/, what I see in the browser's Location field is http://domain.name:9001. What I wish I saw was http://domain.name/App1/, that is, I want the name App1 to remain in the URI, and I'd rather not expose the port number.

Let's say App1 has a link /location/ABC. When I click on it I see http://domain.name:9001/location/ABC when I wish I saw http://domain.name/App1/location/ABC.

Can I achieve this with nginx.conf?

P.S. I put http://domain.name explicitly in the rewrite rule because without it I was getting localhost in the browser, and my browser's localhost is not the same as the server's.

回答1:

Rewrites issue redirects for browser.

If you just want to mount several locations from upstreams - you do not need rewrites, just use:

location /App1/ {
    proxy_pass http://localhost:9001/;
}

But apps should use relative links or account for their absolute location.

For more complex url manipulation you can use break-rewrites:

location /App1/ {
    rewrite ^/App1/(.*) /$1 break;
    proxy_pass http://localhost:9001;
}


标签: nginx