Different behavour of “location” and “proxy_pass”

2020-04-18 09:29发布

I have my nginx conf like :

location ^~ /mount_points/mount_point1 {
  internal;
  alias /repos/mount_point_one;
}

location ^~ /to_proxy {
  internal;
  proxy_pass http://myproxy:5000;
}

When I request for 'http://localhost/mount_points/mount_point1/myfile.zip' I get "/repos/mount_point_one/myfile.zip" as expected.

While request for 'http://localhost/to_proxy/myfile2.html', I get "http://myproxy:5000/to_proxy/myfile2.html".

In the first case, the "/mount_points/mount_point1" part was removed, and in the second case, the "/to_proxy" part still there, I have to fake a "/to_proxy" address in the upstream server to find out this.

Did I missed something? If I just have to rewrite the url, how can I delete the "/to_proxy" part issue to the upstream server?

Thank you.

1条回答
家丑人穷心不美
2楼-- · 2020-04-18 09:48

The proxy_pass directive can perform an aliasing function, but only if an optional URI is provided.

location ^~ /to_proxy/ {
    internal;
    proxy_pass http://myproxy:5000/;
}

To make the alias mapping work correctly, a trailing / is also added to the location parameter.

See this document for details.

If the trailing / on the location parameter causes problems, you can use a rewrite ... break instead:

location ^~ /to_proxy {
    internal;
    rewrite ^/to_proxy(?:/(.*))?$ /$1 break;
    proxy_pass http://myproxy:5000;
}
查看更多
登录 后发表回答