Protecting Folders with Nginx

From Brian Nelson Ramblings
Jump to: navigation, search

Protecting Folders with Nginx

This question comes up every so often, and its actually fairly easy besides the fact you do not use an .htaccess file. To do so we’ll need the auth_basic module which comes included with Nginx.

First we will need to create a password file, you can create this in the folder you wish to protect (though the file can reside anywhere Nginx has access to).

Create the .htpasswd file

htpasswd -c /var/www/domain.com/.htpasswd username

When you run the above command, it will prompt you for a password for the provided username, and then create the file .htpasswd in the folder you specified. If you already have a pre-existing password file, you can omit the -c flag. You can use the -D flag to remove the specified user from a password file.

Setting up Nginx

Adding protection to your admin folder or for wordpress wp-admin folder

server {
... 
    location /admin {
        auth_basic "Welcome to the DarkSide";
        auth_basic_user_file /var/www/domain.com/.htpasswd;
    }
... 
}

With the above access to the admin directory will prompt the user with a basic authentication dialog, and will be challenged against the password file provided.

The password file itself does not have to be named .htpasswd, but if you do store it a web-accessible location make sure to protect it. With the last location block above using any name with a period in front should be protected from web-access.

The safest place to store a password file is outside of the web-accessible location even if you take measures to deny access. If you wish to do so, you can create a protected folder in your nginx/conf directory to store your password files (such as conf/domain.com/folder-name/password) and load the user file from that location in your configuration.