How to redirect only if/after a FAILED basic authentication?

Francis Daly francis at daoine.org
Sun Sep 22 22:04:48 UTC 2013


On Sun, Sep 22, 2013 at 02:14:55PM -0700, jen142 at promessage.com wrote:

Hi there,

> Now, if a visitor:
> 
> 	(1) enters bad (or no) crendentials
> 	(2) clicks "Cancel" on the BASIC auth dialog box
> 
> the site displays a
> 
> 	"401 Authorization Required"
> 
> page.

For accuracy: at point (1), the server sends the 401 response. At point
(2), the browser chooses to display the 401 response that the server had
previously sent.

> Instead, I want to add a rewrite on failed authorization.

Doing that will break http on your server.

Probably not a good idea.

But if you really want to, you can probably configure nginx to do it
for you.

> +               error_page 401 = @redirect;

> I get the redirect on EVERY visit -- never even getting the chance to
> enter credentials; i.e., the rewrite happens apparently BEFORE the auth
> step.

Not quite. Think about the different outputs from

  curl -v http://your-site/

and

  curl -v -u user:pass http://your-site/

and why they happen.

> and that I may have do the @redirect only if some header says "failed".
> 
> How do I redirect ONLY if there's been a failed AUTH?

You get to define what you mean by "failed AUTH", since you don't want
the "no valid credentials were provided" that nginx (and http) uses.

Experiment with something like:

===
  location @needauth {
    auth_basic "Restricted Remote";
    auth_basic_user_file htpasswd;
  }
  location / {
    if ($http_authorization = "") {
      error_page 490 = @needauth;
      return 490;
    }
    auth_basic "Restricted Remote";
    auth_basic_user_file htpasswd;
    error_page 401 = @redirect;
    # and the rest here
  }
===

to see if is close to what you want.

But be aware that when you choose to break http on your server, you get
to deal with any complaints from clients.

Good luck with it,

	f
-- 
Francis Daly        francis at daoine.org



More information about the nginx mailing list