Password protect folders with NGINX

As a follow up to the earlier post regarding unexplained NGINX 404 errors as a condition of a poorly written location block, I thought it might be worth sharing another bad bit of code I have seen in a number of NGINX config files in the wild.  This topic is a bit more serious though as it involves password protecting folders rather than random 404s. It’s pretty common to have a location block that defines a webroot, an index, establishes password protection for the folder, and sets fastcgi params for dynamic page requests like so:

1
2
3
4
5
6
7
location = / {
    root   /var/www/nginx-default;
    index index.php;
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/htpass;
}
include php.conf;

Note, the “include php.conf;” line above is just a quick way we keep our virtual host files clean. The php.conf file contains our location ~ \.php$ block.

The code above is not secure. This location block will only be applied to requests matching “/” exactly (notice the “=” sign). If you access a page or resource directly, you circumvent the authentication entirely! So a request to www.somedomain.com will prompt you for a password, but www.somedomain.com/index.php will let you access index.php.

After a quick jump over to the Nginx wiki we see that using “^~” will allow us to apply a case insensitive regular expression to our location block. This means we are now protecting all contents within the desired folder as well. The wiki also says that a match will result in immediate termination, so be sure to define an additional dynamic page block within your containing location block if necessary (like if you need to run php files within the protected folder for, say, PHPMyAdmin). Notice our included php.conf file has been added within the location block to account for this.

1
2
3
4
5
6
7
8
location ^~ / {
    root   /var/www/nginx-default;
    index index.php;
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/htpass;
    include php.conf;
}
include php.conf;

I personally find the Nginx wiki very readable and very informative. It’s worth taking the 10 minutes to work out solutions from there rather than copy-pasting from blogs. There are some great convention and pitfall articles in there as well. Hope to get to a post outlining our configuration based on some time spent at the wiki.

Leave a comment