打开虚拟主机配置文件
[root@cp1 ~]# cd /usr/local/nginx/conf/vhosts/
[root@cp1 vhosts]# ls
default.conf test.conf
[root@cp1 vhosts]# vim test.conf
修改内容如下:
server
{
listen 80;
server_name www.test.com;
index index.html index.htm index.php;
root /data/www;
Location ! .*admin\.php$ {
auth_basic "aminglinux auth";
auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
}
使用Apache的密码生成工具htpasswd创建一个密码文件,创建第一个用户密码时需要加-c
[root@cp1 vhosts]# /usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/.htpasswd aming
New password:
Re-type new password:
Adding password for user aming
[root@cp1 vhosts]# /usr/local/apache2/bin/htpasswd /usr/local/nginx/conf/.htpasswd aming1
New password:
Re-type new password:
Adding password for user aming1
[root@cp1 vhosts]# cat /usr/local/nginx/conf/.htpasswd
aming:0HeLDJQzx5Hhc
aming1:Uztey/9TxSdig
检查没错重新加载配置
[root@cp1 vhosts]# /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@cp1 vhosts]# /etc/init.d/nginx reload
重新载入 Nginx: [确定]
以管理员身份访问时多了一层保护
使用curl测试
[root@cp1 vhosts]# curl -x127.0.0.1:80 www.test.com/admin.php
401 Authorization Required
[root@cp1 vhosts]# curl -x127.0.0.1:80 -uaming:14721236 www.test.com/admin.php
……
发现php被解析了
访问目录认证可以加上如下内容,如果该目录下没有php文件可以去掉蓝色部分php解析
server
{
listen 80;
server_name www.test.com;
index index.html index.htm index.php;
root /data/www;
location ~ .*admin\.php$ {
auth_basic "aminglinux auth";
auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
location /abc/ {
auth_basic "aminglinux auth";
auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/tmp/www.sock;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name;
}
}