NGINX Proxy_Pass 删除 url 子字符串

Ped*_*dro 13 nginx reverse-proxy regex

我有一个 NGINX 作为反向代理。我需要从 URL 中删除子字符串 string_1,URL 的其余部分是可变的。

例子:

Origin: http://host:port/string_1/string_X/command?xxxxx

Destination: http://internal_host:port/string_X/command?xxxxx
Run Code Online (Sandbox Code Playgroud)

nginx.conf:

location /string_1/   { 

    proxy_pass  http://internal_host:port/$request_uri$query_string;
Run Code Online (Sandbox Code Playgroud)

谢谢,

@pcamacho

Ale*_*Ten 16

这是非常基本和简单的。只需添加/path/部分proxy_pass,nginx 就会location用该路径替换s 前缀。您需要替换/string_1//,所以这样做:

location /string_1/ {
    proxy_pass  http://internal_host:port/;
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该强调后面的斜线,这是一个大问题。没有它,不能正常工作:http://serverfault.com/a/586614/262150 (4认同)
  • 还要注意,如果 proxy_pass 条目正在使用任何其他变量(如主机名的变量),nginx 将停止添加更正后的 `$uri`。您可以使用 `rewrite ^/string_1(.*) $1 break;` 解决方法,然后使用 `proxy_pass http://$host/$uri;`。这个 `$uri` 是正确的,被重写改变了 (3认同)

Ped*_*dro 14

我找到了重写proxy_pass URL的方法:

  location  /string_1/   {  

    if ($request_uri ~* "/string_1/(.*)") { 
            proxy_pass  http://internal_host:port/$1;
    }   

  }
Run Code Online (Sandbox Code Playgroud)

问候,

@pcamacho