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?
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/).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With