nginx,为什么不能在 if 部分使用 auth_request

kol*_*oly 8 java nginx

我正在尝试仅针对 Nginx 中的 POST 方法发出自定义身份验证请求。我找到了 auth_request 模块,所以我写了这样的东西:

location /api/books {
  if ($request_method = GET) {
     proxy_pass http://bookservice;
  }
  auth_request /api/auth;
  proxy_pass http://bookservice;
}
location /api/auth {
  proxy_pass http://authservice;
}
Run Code Online (Sandbox Code Playgroud)

bookservice 和 authservice 是两个上游。我第一次尝试这个,它不起作用:每次有 GET /api/books 时,它都会触发对身份验证服务的子请求。预期的行为是:当它是 GET /api/books 时,它不会向 auth 服务发出子请求,否则,它会向 auth 服务发出子请求。

所以我写了类似的东西:

location /api/books {
  if ($request_method = GET) {
     proxy_pass http://bookservice;
  }
  if ($request_method = POST) {
    auth_request /api/auth;
    proxy_pass http://bookservice;
  }
}
location /api/auth {
  proxy_pass http://authservice;
}
Run Code Online (Sandbox Code Playgroud)

但是当重新加载配置时,它说:“auth_request”指令在这里是不允许的。

我知道 auth_request 不能在 if 中,它只能在位置、服务器、http 中。但是如何实现我的目标,为什么不能在if里面应用呢?

use*_*889 5

我今天做了这样的事情。来到这个解决方案:

location /api/books {
    if ($request_method = POST) {
        rewrite .* /_api/books last;
    }
    proxy_pass http://bookservice;
}

location /_api/books {
    rewrite .* /api/books break;
    auth_request /api/auth;
    proxy_pass http://bookservice;
    internal;
}
Run Code Online (Sandbox Code Playgroud)

http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

如果使用 if 会更好,但我不知道为什么不允许这样做。但是,nginx 不鼓励“如果”(https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/)。

  • 您可能想添加“内部;” 指令到您的 _api 位置,因此只能通过 nginx 重写来访问它。 (2认同)