NGINX Basic Authentication

Required package

  • For Debian: apache2-utils.

    sudo apt-get install apache2-utils
    
  • For Fedora: httpd-tools.

    sudo dnf install httpd-tools
    

Create password file

Run with -c option if /etc/nginx/.htpasswd does not exist:

sudo htpasswd -c /etc/nginx/.htpasswd user1

If .htpasswd already exists, don’t use -c option or file will be overwritten.
To add more user to password file.

sudo htpasswd /etc/nginx/.htpasswd user2

Configure NGINX

Authentication for specific location

location /test {
	auth_basic "Test Authentication";
	auth_basic_user_file /etc/nginx/.htpasswd;
	...
}

Authentication for whole website but off for specific location

server {
	...
	auth_basic "Test Authentication";
	auth_basic_user_file /etc/nginx/.htpasswd;

	...
	location /test {
		auth_basic off;
	}
}

Restart NGINX

sudo service nginx restart

You will see a prompt to login when access to the page.

Source

nginx 
comments powered by Disqus