Password Protecting Nginx

Create username/password

Use htpasswd.
If /etc/apache2/.htpasswd doesn’t already exist, pass the -c flag in the following command.

sudo htpasswd /etc/apache2/.htpasswd username_here

You’ll be prompted for a password.

You can check the file’s contents with cat. It’ll be username:ha$h3dP@ssWord9p80uwjlrf pairs.

Use HTTP basic auth in NGINX

Use either on an entire server or just a location (both shown below):

server {
  auth_basic 			"Some message"; 			# for entire site.
  auth_basic_user_file  /etc/apache2/.htpasswd;
  
  location /public/ {
  	auth_basic off; 	# disable for a public area
  }
  
  ...
  
  location /secret_spot {
	  auth_basic 			"Some message"; 		# for a location.
	  auth_basic_user_file  /etc/apache2/.htpasswd;
  }
}
#linux #guides