How to password protect an NGINX website

Here are the steps to password protect an NGINX website:

1. Logon to the server

You need SSH to solve this problem.

2. Create a .htpasswd file

This is the file that will contain the password. There is a special Linux utility called `htpasswd` which generates the password file. The syntax is:

htpasswd -c /home/sitename/public_html/.htpasswd username

The last part of the command specifies the username.

The filename can be called anything, we just chose .htpasswd for consistency. The . is a must and means it’s a hidden file.

3. The next step depends on which flavour of NGINX you have. You basically have to go and look for the NGINX configuration file for your website. If you’re working on a shared server, you will most likely find a whole bunch of sitename.com.conf files in:

cd /etc/nginx/sites-available/
ls

or if you’re using Midnight Command as an editor you could edit the file directly with:

mc -e /etc/nginx/sites-available/sitename.com.conf

Next you need to find a section called location / {} If you can’t find the section, create it.

Inside this file you’ll be adding auth_basic and auth_basic_user_fileas below:

location / {
   auth_basic "Restricted";
   auth_basic_user_file /home/sitename/public_html/.htpasswd;
   try_files $uri $uri/ /index.php?$query_string;
}

In this example "Restricted" is the title of the dialogue box that will pop up. Remember to put semicolons ; after each line.

4. Once you’re done, reload NGINX so that it can pick up the configuration changes.

service nginx reload

Reference

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top