Search code examples
authenticationnginxbasic-authentication

Nginx Basic Auth working on directory, but not files


i just started working on nginx, switching to it after working with apache for years. Currently, I am trying to get HTTP Basic Auth working. With the config down there, I get an Basic Auth Dialog in Chrome if I go to https://www.website.com/doe. But - if I try to go to the domain https://www.website.com/doe/importanttext.csv - it will not ask for an auth, but instead just download the file. How can I protect folders completly - with all content?

Thanks

server {
[SSL and Server Stuff]

    location ^~ /doe/ {
            auth_basic "Admin Access";
            auth_basic_user_file  /var/www/doe/.htpasswd;
    }


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

    location ~ \.php$ {
            try_files $uri = 404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

    location ~ /\.ht {
            deny all;
    }

}

Solution

  • I found my error, I was using

    auth_basic "Admin Access";

    however, to protect the files within the folder, it needs to be

    auth_basic "Restricted";

    Nginx stops looking for location matches if it finds a matching one and then does only navigate in this path. So if I want to also use php and .ht protection within that protected subfolder, I also need to include these directives there as well - as shown beneath.

    server {
    [SSL and Server Stuff]
    
    location ^~ /doe/ {
            auth_basic "Admin Access";
            auth_basic_user_file  /var/www/doe/.htpasswd;
    
    location ~ \.php$ {
            try_files $uri = 404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
    
    location ~ /\.ht {
            deny all;
    }
    }
    
    
    location / {
            try_files $uri $uri/ =404;
    }
    
    location ~ \.php$ {
            try_files $uri = 404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
    
    location ~ /\.ht {
            deny all;
    }
    
    }