How to protect password a folder in Nginx


Example: we need protect folder /home/nginx/domains/tutorialspots.com/public/secure with a username and password.

Step 1: login server via SSH
Step 2: create file .htpasswd eg: /home/nginx/domains/tutorialspots.com/public/secure/.htpasswd

htpasswd -c /home/nginx/domains/tutorialspots.com/public/secure/.htpasswd username

you can replace username with your name login eg: admin

Then you will see:

New password: 
Re-type new password: 
Adding password for user username

Example result:

[root@tutorialspots ~]# htpasswd -c /home/nginx/domains/tutorialspots.com/public/secure/.htpassw
d username
New password:
Re-type new password:
Adding password for user username

You will get file .htaccess with content like:

username:/oyDJOpffkNA6

You can use this command to generate your own .htpasswd content.

htpasswd -nb username password

Result:

[root@tutorialspots ~]# htpasswd -nb username password
username:1JefVZClEkUZ6

Note: if you get error: command not found means your server doesn’t contains htpasswd, you must install it:

yum install httpd-tools

Step 3: open file conf of this domain eg: /usr/local/nginx/conf/conf.d/tutorialspots.com.conf then add these lines:

location /secure {
  auth_basic "Restricted";
  auth_basic_user_file /home/nginx/domains/tutorialspots.com/public/secure/.htpasswd;
}

protect password a folder in Nginx

Step 4: restart nginx

service nginx restart

Done! now try to access http://tutorialspots.com/secure.

1 Comment

Leave a Reply