Nginx: password protect a directory

Nginx is a very powerful webserver, often used as a replacement to Apache for its speed. With Apache, you can very easily protect a directory with a custom username/password by using a .htaccess file. Nginx does not support that (since it’s a performance bottleneck), but it does offer a replacement.

This uses the auth_basic nginx module which is available in nearly every installation of Nginx if you install it via a yum or apt repository.

Create a secure username and password combination#

The first step is to generate a secure username and password to use. If you’re out of ideas and want a random password, I offer a password generator for that. At the command line of your server, type the following commands.

# mkdir -p /etc/nginx/passwd.d/
# htpasswd -c /etc/nginx/passwd.d/secure.passwd username

The above will create a directory called “/etc/nginx/passwd.d/” and will next prompt you for a password for the “username” user. If the file already exists, because you’re adding multiple users, you can leave out the -c flag. The “-c” tells the htpasswd command to create a new file. You now have a file outside of your public directory with a secure username and password in it. Never store that secure.passwd file in your webroot, it should never ever be accessible via the webserver document root.

The configuration in Nginx#

To secure a directory, use a configuration as follows.

server {
    listen 80;
    server_name mydomain.be;
 
    root /var/www/mydomain.be/htdocs;
    index index.html index.php;
 
    location /securedpage {
        auth_basic "Please enter valid credentials";
        auth_basic_user_file /etc/nginx/passwd.d/secure.passwd;
    }
}

That configuration snippet above will protect the directory “/securedpage” with the username and password you defined in the /etc/nginx/passwd.d/secure.passwd file.