title: Nginx - how to redirect to login page after auth_request returns 401
body: <p>I do <code>auth_request /auth;</code>
  as described in <a href="https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-subrequest-authentication/" rel="nofollow noreferrer">configuring-subrequest-authentication/</a></p>
  <p>How can I redirect to login page if /auth returns 401 or 403?</p>
  <p>I tried with</p>
  <pre><code>error_page 401 403 = @error401;
  
      location = ^/securedUrl {
          add_header dbg-header dbg_ws_3;
          auth_request /auth;
          proxy_pass http://auth-module:8080;
          proxy_http_version 1.1;
          proxy_set_header Host      $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection &quot;upgrade&quot;;
          proxy_pass_header x-remaining-session-time;
      }
  
  location @error401 {
    return 302 /login-module/login;
  }
  
  location = /auth {
    internal;
    rewrite ^/(.*) /is-authorized break;
    proxy_pass http://auth-module:8080;
    proxy_pass_request_body off;
    proxy_set_header Content-Length &quot;&quot;;
    proxy_set_header X-Original-URI $request_uri;
  }
  </code></pre>
  <p>but it doesn't work, I get 401 in browser</p>