编辑配置文件vim /usr/local/nginx/conf/vhost/test.com.conf
server { listen 80; server_name test.com; index index.html index.htm index.php; root /data/wwwroot/test.com; location / { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; } }
生成密码文件
#用httpd密码生成工具 yum install -y httpd htpasswd -c /usr/local/nginx/conf/htpasswd chyuanliu
对nginx测试配置并重新加载
//生成网站文件夹 mkdir /data/wwwroot/test.com echo “test.com”>/data/wwwroot/test.com/index.html
测试网站
[root@localhost ~]# curl -x127.0.0.1:80 test.com -I HTTP/1.1 401 Unauthorized Server: nginx/1.12.1 Date: Wed, 16 May 2018 18:48:58 GMT Content-Type: text/html Content-Length: 195 Connection: keep-alive WWW-Authenticate: Basic realm="Auth" [root@localhost ~]# curl -uchyuanliu:123qwe -x127.0.0.1:80 test.com “test.com”
编辑windows的hosts文件,然后在浏览器中访问test.com会有输入用户、密码的弹窗
针对目录进行用户验证
location /admin/ { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; }
[root@localhost ~]# mkdir /data/wwwroot/test.com/admin [root@localhost ~]# echo "test.com admin dir" > /data/wwwroot/test.com/admin/index.html [root@localhost ~]# vi /usr/local/nginx/conf/vhost/test.com.conf [root@localhost ~]# /usr/local/nginx/sbin/nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful [root@localhost ~]# /usr/local/nginx/sbin/nginx -s reload [root@localhost ~]# curl -x127.0.0.1:80 test.com/admin/ <html> <head><title>401 Authorization Required</title></head> <body bgcolor="white"> <center><h1>401 Authorization Required</h1></center> <hr><center>nginx/1.12.1</center> </body> </html> [root@localhost ~]# curl -uchyuanliu:123qwe -x127.0.0.1:80 test.com/admin/ test.com admin dir