edenisn
edenisn

Reputation: 155

nginx auth_request redirect

I use auth_request module(http://nginx.org/en/docs/http/ngx_http_auth_request_module.html). My nginx config:

auth_request /auth;
auth_request_set $backend_status $upstream_status;

location / {
    proxy_pass http://unicorn;

    error_page 401 @auth;
}

location = /auth {
    internal;
    proxy_pass https://proxy_pass_url;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
}

location @auth {
    if ($backend_status = "401") {
      return 302 https://proxy_pass_url/login? origin=$scheme://$http_host$request_uri;
    }
}

But my redirect doesn't work. What's wrong in my config?

Upvotes: 5

Views: 5408

Answers (2)

Alexander Klimenko
Alexander Klimenko

Reputation: 2280

auth_request_set variables are not accessible inside if blocks, but are available inside access_by_lua, which provides if-statements.

      access_by_lua_block {
        if ngx.var["backend_status"] == "401" then
          return ngx.redirect("https://proxy_pass_url/login? origin=" .. $scheme .. "://" .. $http_host .. $request_uri)
        end
      }

Upvotes: 0

Piotr Krawcow
Piotr Krawcow

Reputation: 39

What do you mean it doesn't work? I assume you are not redirecting, but what is the status code of the request? What is the status code of the /auth sub-request? On which nginx do you test it? Did you check the error/access log?

I'm asking because I took your code, run on Nginx 1.19.1 and it works well. When the /auth sub-request returns a 401 error, I'm redirecting via @auth location. One thing we can improve here. You don't need to check if the $backend_status variable equals to 401, If Nginx passes the request to the @auth location, it means, that we have 401 from /auth :)

Br, Piotr

Upvotes: -1

Related Questions