Password protect directories / folders with nginx

Overview

On an Apache server, it’s possible to password protect a directory using .htaccess and .htpasswd files. However, .htaccess files are not supported on Nginx.

You can still password protect your directories, but you need to use a basic_auth.conf file instead.

Creating the file

  1. Log into your server via SSH.
  2. Navigate to your user’s directory.
  3. Make sure you have a /home/username/nginx/example.com directory.This doesn’t exist by default; you must create it by running the following:
    sudo mkdir -p nginx/example.com
  4. In this /home/username/nginx/example.com directory, add a file named ‘basic_auth.conf‘ with the following:
    location / {
            auth_basic "Restricted";
            auth_basic_user_file /home/username/nginx/example.com/.htpasswd;
    }

    * The auth_basic parameter is just the title of the prompt the user sees when visiting this directory.
    * The auth_basic_user_file parameter specifies where the password file is. Note how its path is set to the /nginx directory.

    In this example, the ‘location’ directive password protects the entire domain since it’s pointing to ‘/’.
    If you want a subdirectory to be password protected, change the ‘location’ directive as follows:

    location /subdirectory/
  5. Run the following to create the .htpasswd file:
    sudo htpasswd -c /home/username/nginx/example.com/.htpasswd LOGIN

    * LOGIN is the username you want to be used to authenticate in the login prompt.

  6. After typing that command, enter a password and confirm it when prompted:
    New password: 
    
    Re-type new password:

    Adding password for user LOGIN

  7. Reload the nginx config file.
    sudo service nginx reload
  8. In your browser, load the directory your /home/username/nginx/example.com/basic_auth.conf points to. *In the example above, this would be your domain’s root directory since the ‘location’ directive points to /.
  9. Enter a user/password when prompted to log in.
    * In this example, your username is LOGIN and the password is the one you created above.

See also:

Leave a Comment