1、找到nginx.conf文件,在nginx.conf 文件中对应的 server 段中 添加引用:

    location ^~ /test/
    {
        auth_basic "Please enter Password";
        auth_basic_user_file /usr/local/nginx/conf/vhosts/htpassword;
    }

如果想限制某一个目录的话需要如下配置:

location ^~ /test/ {
auth_basic "TEST-Login!";
auth_basic_user_file /opt/nginxpwd;
}

如果 不用 ^~ /test/ 而用 /test 的话 那么将只能对目录进行验证直接访问其下的文件,将不会弹出登录验证,所以我们也不能写,这样访问目录要验证,但是直接访问文件不需要。(Deven:之前遇到一个奇怪了问题,就是一样的配置在A服务器可以,但是B服务器输入密码之后提示500错误,这个时候要去看一下web error log,一般是没有权限读取密码文件 )

 location /
{
auth_basic "Please enter Password";
auth_basic_user_file /usr/local/nginx/conf/vhosts/htpassword;
}

2、创建密码文件htpassword

vi  /usr/local/nginx/conf/vhosts/nginx_htpasswd.pl

内容如下(先输入以下脚本生成加密串):

#!/usr/bin/perl
use strict;
my $pw=$ARGV[0];
print crypt($pw,$pw)."\n";

保存以上内容。

进入命令行执行以下命令:

chmod +x  /usr/local/nginx/conf/vhosts/nginx_htpasswd.pl
/usr/local/nginx/conf/vhosts/nginx_htpasswd.pl 123456
执行后系统会输出123456对应的密文,将密文拷贝一份,打开htpassword文件,将密文以格式“用户名:密码密文”填入文件内容中。

以上配置好以后,从新启动nginx。

 

参考:http://www.vpser.net/build/nginx-htpasswd.html

http://liningjustsoso.iteye.com/blog/1563317

http://blog.chinaunix.net/uid-20377663-id-3016520.html