为了安全,有时我们不希望暴露网站的地址,特别是后台管理地址。如 http://www.servername/admin.php. 我们一般会把admin.php改为 别的不容易猜测的文件名,但是针对一些开源或其他原因程序过分绑死路径,不好修改 admin.php文件,就算成功修改了,后面也不方便 进行升级。此时我们就可以利用 nginx auth basic 功能,给予http指定访问目录添加basic认证。
1.在 nginx/conf/ 下创建目录和文件
mkdir auth_pwd
touch auth_pwd/auth.pwd
chown -R www:root auth_pwd/auth.pwd
auth.pwd 书写格式是: 用户名:密码
, 每行一个账户, 并且密码必须使用函数 crypt(3) 加密。 可以使用 php 对密码进行加密
echo crypt('123456', base64_encode('123456')); //输出结果 MTyr2pdlzUees
将用户和密码写入 auth.pwd
文件里
test:MTyr2pdlzUees
2.在 nginx 指定站点 .conf 下 配置 auth basic
#eg1. 对站点所有访问都进行 认证
server {
#listen [::]:80;
server_name www.servername.com;
index index.html index.htm index.php default.html default.htm default.php;
root /web/;
auth_basic "please input your name and password";
auth_basic_user_file auth_pwd/auth.pwd;
...
}
#eg2. 对 admin 目录下的文件进行 认证
location ~ ^/admin/.* {
auth_basic "please input your name and password";
auth_basic_user_file auth_pwd/auth.pwd;
}
auth_basic
是提示信息,auth_basic_user_file
是存放用户名和密码的文件的路径