How to password protect NGINX directories

TL;DR

mc -e /etc/nginx/nginx.conf

location / {
   auth_basic "Restricted";
   auth_basic_user_file /home/domain//public_html/.htpasswd;
}

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

Now restart NGINX:

# service nginx restart

The / location is pretty important, and if you’re doing other stuff in there, e.g. with WordPress or Laravel friendly URL rewriting, then you have to combine like this:

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

Reference:
https://help.dreamhost.com/hc/en-us/articles/215837528-Password-protecting-directories-with-Nginx

Share this article

Leave a Reply

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

Scroll to Top