Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx, why auth_request cannot be used in if section

Tags:

java

nginx

I am trying to make a custom authentication request only for POST method in Nginx. And I found auth_request module, so I wrote something like this:

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;
}

bookservice and authservice are two upstreams. I first tried this, it doesn't work: everytime there is a GET /api/books, it fires the subrequest to auth service. The expected behavior is: when it is GET /api/books, it does NOT fire subrequest to auth service, otherwise, it fires the subrequest to auth service.

So I wrote something like:

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;
}

But when reloading the config, it says: "auth_request" directive is not allowed here in.

I understand that auth_request cannot be in if, it can only be in location, server, http. But how to achieve my objective, and why it cannot be applied inside if?

like image 991
koly Avatar asked Jul 18 '16 07:07

koly


1 Answers

I did something like this today. Came to this solution:

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;
}

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

Would be much nicer with an if, but I don't know why it isn't allowed. However "if" is discouraged by nginx (https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/).

like image 154
user3784889 Avatar answered Sep 21 '22 08:09

user3784889