Custom 401 page not prompting for credentials on nginx
Asked Answered
S

2

5

I have a part of my website protected by auth_basic :

    location / {
            auth_basic "Authorization Required";
            auth_basic_user_file .htpasswd;
            index  app.php;
            try_files $uri @rewriteapp;
    }

For unauthorized users (those who click 'Cancel'), I'd like to display a custom error page. Here's how I've done it :

    error_page 401 = @error401;

    location @error401 {
                    rewrite ^ /error/401.html redirect;
    }

    location /error {
            expires max;
            add_header Pragma public;
            add_header Cache-Control "public";
            index  app.php;
            try_files $uri @rewriteapp;
    }

I had to create the @error401 alias so I could specify "Redirect", because if I used the internal redirection, my app would handle the original request (and give access to the actual requested page !)

So this works fine, the page displays. The problem is that now nginx doesn't even ask users for there credentials.

Is there any way to fix this ? Or any better way to handle this issue ?

Scholem answered 24/1, 2013 at 12:7 Comment(0)
P
5

This is how I was able to accomplish what you're trying to do:

## Path must be prefixed with a /, i.e. /401.html, NOT 401.html
error_page 401 /401.html;

location ~ (401.html)$ {
    alias /usr/share/nginx/html/$1;
}
Primateship answered 1/2, 2013 at 22:2 Comment(2)
Thanks, your answer needs some customization because it needs to serve a PHP file and not a static one, but I'll try if I can adapt it.Scholem
@Scholem did you find a solution to the redirect problem ? The error clause/redirect simply ignores authentication at all and rewrites firstDimarco
A
3

You should add auth_basic off;

Aho answered 15/11, 2015 at 6:59 Comment(3)
This actually helped me displaying the custom 401 page instead of the built in nginx 401 page. A better description where to add auth_basic off would be better. I had to add it in location = /40x.html {} block.Taxaceous
Great answer. It helped me with an issue I had for so many days.Incinerator
should be "off" instead of offAbrahan

© 2022 - 2024 — McMap. All rights reserved.