Nginx authentication and custom error page

http-basic-authenticationnginx

I'm trying to set up my server so that it requires authentication before browsing any file on the domain. However, I want to display a custom error page (placeholder.html) when someone fails to authenticate.

I tried the server configuration listed below, but it sends my browser into an infinite redirect loop (without even presenting an authentication window). Can anyone explain that? How would you solve this?

server {
        listen 80;
        server_name example.com;

        root /var/www/example.com;
        index index.html index.htm;

        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/auth/example.com.auth;

        error_page 401 placeholder.html;

        location = placeholder.html {
                auth_basic off;
        }

        location / {
                try_files $uri $uri/ =404;
        }
}

Best Answer

You have to add a leading slash before placeholder.html in both location and error_page directives.