Nginx auth basic not working with rewrite

http-basic-authenticationnginxrewrite

I need to protect one directory with the basic auth and rewrite all urls inside this directory only.

I have the following config:

    location /admin/ {
            auth_basic "Secure area";
            auth_basic_user_file .htpasswd;
            rewrite  ^(.*)$ /admin/index.php last; break;
    }

However, basic auth not working. If I comment rewrite rule it starts working.

How to fix it?

Best Answer

"rewrite" goes before basic auth, because of request workflow.

try trick with error page and named location:

 location /admin/ {
            auth_basic "Secure area";
            auth_basic_user_file .htpasswd;
            error_page 404 = @admin;
    }

location @admin {
            rewrite  ^(.*)$ /admin/index.php last;
}
Related Topic