.htpasswd reads log files such as the /var/log/auth.log file that contain password authorisation failure reports and bans the corresponding IP addresses using firewall rules.
Unlike Apache, nginx does not have any .htaccess file. Password protection is achieved by using the Nginx HttpAuthBasic module directives in the configuration file.To password protect a directory called restricted_folder, use the following directives inside the server block in the configuration file (/etc/nginx/sites-available/default) for your website.
location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } # password protect this directory location ^~ /restricted_folder/ { auth_basic_user_file conf/.htpasswd; }
This will password protect the directory called "restricted_folder", it’s sub folders and the files inside it.
Change auth_basic_user_file directive to point to your .htpasswd file. I am using nginx version: nginx/1.10.1 (Ubuntu), note that the filename path is relative to directory of nginx configuration file, nginx.conf, rather than nginx prefix directory. So, if your nginx.conf is in /etc/nginx folder, the above code will use the htpasswd file in /etc/nginx/conf folder.
To create an htpasswd file (for htaccess "authentication") here’s the format of the htpasswd file :
user:pass user2:pass2:comment user3:pass3
Passwords must be encoded by the crypt(3) function if Apache is not installed To create your file, without installing Apache, just run:
printf "USER:$(openssl passwd -crypt PASSWORD) :comment \n " >> /etc/nginx/conf.d/.htpasswd
Remember you need to replace USER and PASSWORD for your user and password