某些情况需要为Nginx网站的某个目录设置访问验证,此处以http://localhost/phpMyAdmin/目录为例进行配置,为该目录设置HTTP访问认证。

###Demo:/usr/local/nginx/conf/nginx.conf
root /home/wwwroot/default/;
index index.html index.htm index.php;
location / {
}
###STEP1:Create htpasswd
username:Exb4YvxLWWwNo #htpasswd规则:用户名:加密密码(每行一个),此处以用户名user密码123456为例
##方法1:使用Apache2生成
yum install apache2-utils htpasswd /usr/local/nginx/conf/htpasswd user 123456 123456
##方法2:使用pl程序生成
wget -c http://trac.edgewall.org/export/10890/trunk/contrib/htpasswd.py ./htpasswd.py -b -c /usr/local/nginx/conf/htpasswd user 123456
##方法3:使用openssl生成
printf "user:$(openssl passwd -crypt 123456)\n" >>/usr/local/nginx/conf/htpasswd
cat /usr/local/nginx/conf/htpasswd #查看htpasswd内容是否生成
###STEP2:Set location
##方法1:适用于9000端口
location ^~ /phpMyAdmin {
#注意正则表达式的写法,此写法用于强制认证访问该路径,但同时也会导致该路径下的php不解析而直接下载
#location ~ .*\.(php|php5)?$ {
#设置解析php与php5
location ~ .*\.php$ {
#设置解析php
#root /home/wwwroot/default;
#如果$document_root不是默认的网站路径需重新定义root路径,此路径不正确会导致403、502错误
fast_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#如果使用fast_pass 127.0.0.1:9000;出现502错误加上此句
include fastcgi_params;
}
auth_basic "Authorized users only";
auth_basic_user_file htpasswd;
}
##方法2:适用于unix套接字,如一键lnmp安装包(lnmp.org)
location ^~ /phpMyAdmin {
#注意正则表达式的写法,此写法用于强制认证访问该路径,但同时也会导致该路径下的php不解析而直接下载
#location ~ .*\.(php|php5)?$ {
#设置解析php与php5
location ~ .*\.php$ {
#设置解析php
fastcgi_pass unix:/tmp/php-cgi.sock;
#一键lnmp安装包(lnmp.org)默认使用unix套接字,使用fast_pass 127.0.0.1:9000;会出现502错误
fastcgi_index index.php;
include fastcgi.conf;
}
auth_basic "Authorized users only";
auth_basic_user_file htpasswd;
}
nginx -t #测试配置是否有错误 nginx -s reload #重载配置文件
本文标题:Nginx设置目录HTTP访问认证
版权声明:本文使用「署名 4.0 国际」创作共享协议,转载或使用请遵守署名协议。
上一篇:青春不散场 后会有期