Custom 401 page not prompting for credentials on nginx

Julien picture Julien · Jan 24, 2013 · Viewed 8.4k times · Source

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 ?

Answer

Jason Barnett picture Jason Barnett · Feb 1, 2013

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;
}