Nginx捕获并将所有以/ api开头的请求重写为代理

时间:2020-01-03 20:25:40

标签: nginx proxy

我想将所有具有/api/http://example.com/api/)的请求重定向到我的代理应用程序,并在此过程中删除/api。我已经尝试过了,但是在卷曲时得到了404。它无法到达应用程序,我认为这与rewrite有关,但是我不确定它是否正确。

location ~ ^/api {
  rewrite ^/api/(.*) /$1 break;
  proxy_pass http://127.0.0.1:8070;
}

以下内容在硬编码时有效。它将我重定向到我的应用程序/error

location = /api/error {
  proxy_pass http://127.0.0.1:8070/error;
}

例如,我希望http://example.com/api/loginhttp://example.com/login一样打我的代理应用程序。

1 个答案:

答案 0 :(得分:0)

这对我有用。 $1$is_args$args部分传递URL中/api之后的所有内容。现在,进入我的域时,example.com/api/something/something传递给我的代理应用程序。

location ~/api(.*)$ {
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header Host $host;
  proxy_pass http://127.0.0.1:8070$1$is_args$args;
}