Nginx如何配置HTTP基本认证


生成密码

htpasswd -c /usr/local/nginx/conf/.htpasswd admin

Configure HTTP Authentication for Nginx

As we mentioned earlier on, you can restrict access to your webserver, a single web site (using its server block) or a location directive. Two useful directives can be used to achieve this.

  • auth_basic – turns on validation of user name and password using the “HTTP Basic Authentication” protocol.
  • auth_basic_user_file – specifies the password file.


Password Protect Nginx Virtual Hosts

To implement basic authentication for the whole web server, which applies to all server blocks, open the /etc/nginx/nginx.conf file and add the lines below in the http context:

http{
	auth_basic           "Restricted Access!";
    	auth_basic_user_file /etc/nginx/conf.d/.htpasswd; 
	……...
}



Password Protect Nginx Website or Domain

To enable basic authentication for a particular domain or sub-domain, open its configuration file under /etc/nginx/conf.d/ or /etc/nginx/conf/sites-available (depending on how you installed Nginx), then add the configuration below in server block or context:

server {
	listen 			80;
	server_name    	  example.com;
	auth_basic           	"Restricted Access!";
    	auth_basic_user_file 	/etc/nginx/conf.d/.htpasswd; 
	location /  {
		……..
	}
	……...
}


Password Protect Web Directory in Nginx

You can also enable basic authentication within a location directive. In the example below, all users trying to access the /admin location block will be asked to authenticate.

server {
	listen 			80;
	server_name    	example.com www.example.com;
	
	location / {
		……..
	}
	location /admin/ {
		auth_basic           	"Restricted Access!";
    		auth_basic_user_file 	/etc/nginx/conf.d/.htpasswd; 
	}

	location /public/{
		auth_basic  off;	#turns off basic http authentication off for this block
	}
	……..
}


阅读量: 503
发布于:
修改于: