来自路由的Nginx proxy_pass,不带尾部斜杠

xsuvu9jc  于 2023-01-29  发布在  Nginx
关注(0)|答案(1)|浏览(147)

我想配置Nginx在我的域代理上有一个路由到另一个URL。更具体地说,我想my.domain.com/special_route代理到another.domain.com,而URL在地址栏中保持不变。例如,我想my.domain.com/special_route/some_path代理到another.domain.com/some_path,而URL保持不变。
这是我到目前为止添加的配置:

set $another_url https://another.domain.com;
  
  location ~ /special_route(/?.*)$ {
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

    add_header 'Access-Control-Allow-Origin' '*';

    proxy_pass $another_url$1;
  }

它看起来像预期的那样工作,但有一个明显的例外。my.domain.com/special_route/some_path工作,my.domain.com/special_route/也工作。但是,my.domain.com/special_route(没有尾部斜杠)不工作。它看起来像是another.domain.com/special_route的代理。
我需要更改或添加什么到我的配置中,才能让基本路由在没有尾部斜杠的情况下工作?

euoag5mw

euoag5mw1#

$1为空时,它就变成了proxy_pass http://upstream,这意味着url被完整地传递到后端(/special_route)。
在这种情况下,变量需要更新为/。这是一个可行的方法:

# tip: it should start with ^/ unless you do mean
# to allow accessing /thing/special_route in the same fashion
location ~ ^/special_route(/?.*)$ {
  proxy_set_header   Host             $host;
  proxy_set_header   X-Real-IP        $remote_addr;
  # another tip: unless you know what you're doing,
  # don't use $proxy_add_x_forwarded_for. Just use $remote_addr
  # otherwise people may be able to fake their ip in some cases
  proxy_set_header   X-Forwarded-For  $remote_addr;

  add_header 'Access-Control-Allow-Origin' '*';

  set $proxy_url $1;
  if ($proxy_url = '') {
    set $proxy_url /;
  }
  proxy_pass $another_url$proxy_url;
}

相关问题