Darshan Montgomery
Darshan Montgomery

Reputation: 83

Nginx password protected directory not working for deeper links

I have an Nginx password protected directory that works just fine if you go to mydomain.com/protected_folder/. However if I go to mydomain.com/protected_folder/index.php the page loads up just fine... and it shouldn't.

How do I set up my location block to completely block all access past the protected directory?

My block:

location /protected_folder {
        try_files $uri $uri/ =404;
        auth_basic "Protected Folder Login";
        auth_basic_user_file /etc/nginx/my_pass;
         }

As a side note. When I had the whole site password protected this was not an issue.

Upvotes: 1

Views: 867

Answers (1)

Richard Smith
Richard Smith

Reputation: 49812

The problem is that .php files are not processed by this location block. They are processed by a location block such as location ~ \.php$.

If you use the ^~ modifier, you will force this location block to have a higher precedence than the regular expression location block. See this document for details.

This will of course prevent //mydomain.com/protected_folder/index.php from executing correctly. To correct this, you will need a nested location ~ \.php$ block to handle .php files under the /protected_folder.

For example:

root /path/to/root;

location ^~ /protected_folder {
    try_files $uri $uri/ =404;
    auth_basic "Protected Folder Login";
    auth_basic_user_file /etc/nginx/my_pass;

    location ~ \.php$ {
        ...
    }
}

location ~ \.php$ {
    ...
}

The nested location ~ \.php$ block is a duplicate of the existing location ~ \.php$ block within the server block.

Upvotes: 3

Related Questions