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; } } auth_basic:定义用户认证的名字 auth_basic_user_file:用户名密码文件

• yum install -y httpd • /usr/bin/htpasswd -c /usr/local/nginx/conf/htpasswd lsx //需要用到Apache的htpasswd工具。-c 后面指定生成密码文件的路径 /usr/bin/htpasswd /usr/local/nginx/conf/htpasswd lshx //在次创建用户不需要-c New password: Re-type new password: cat /usr/local/nginx/conf/htpasswd lsx:$apr1$/TT4ltP7$cAIoPauMzfObrxUoO.Lxv0 lshx:$apr1$u/csEPsG$S1dMwu2u.TRDTvl4x9VDv.

-t && -s reload //测试配置并重新加载 -s reload 的好处是修改的文件有错误不会去破坏程序 测试: mkdir /data/wwwroot/test.com echo “test.com”>/data/wwwroot/test.com/index.html curl -x192.168.211.152:80 wiki.com -I //状态码为401说明需要验证 HTTP/1.1 401 Unauthorized man curl -u --user user:password curl -uaming:passwd 编辑windows的hosts文件,然后在浏览器中访问test.com会有输入用户、密码的弹窗 curl -ulsx:123 -x192.168.211.152:80 wiki.com -I //访问状态码变为200 HTTP/1.1 200 OK 以上是针对整站认证 下面针对站点下的某个目录 location /admin/ { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; } 测试: curl -x192.168.211.152:80 wiki.com/lsx -I //这里设置目录lsx HTTP/1.1 401 Unauthorized echo "123">/data/wwwroot/test/lsx/index.html curl -ulsx:123 -x192.168.211.152:80 test.com/lsx/index.html 123