Nginx给网站添加用户认证配置( Basic HTTP authentication)

说明:
ngx_http_auth_basic_module
模块实现让访问者只有输入正确的用户密码才允许访问
web
内容。
web
上的一些内容不想被其他人知道,但是又想让部分人看到。
nginx
的
http auth
模块以及
Apache http auth
都是很好的解决方案。

这里以军哥的
LNMP
为例,默认情况下
nginx
已经安装了
ngx_http_auth_basic_module
模块。
Nginx认证配置实例
1、生成认证文件
# printf "test:$(openssl passwd -crypt 123456)\n" >>/home/htpasswd
# cat /home/htpasswd
test:xyJkVhXGAZ8tM
注意:
这里账号:
test
,密码:
123456
,记住认证文件路径
2、配置网站conf文件
server{
listen 80;
server_name www.moerats.com moerats.com;
index index.html index.php;
root /home/wwwroot/www.moerats.com;
location /
auth_basic "Please enter your username and password";
auth_basic_user_file /home/htpasswd;
autoindex on;
}
注意:
一定要注意
auth_basic_user_file
路径,否则会不厌其烦的出现403。
3、重启Nginx
/etc/init.d/nginx restart
LNMP下为Nginx目录设置访问验证的用户名密码
有时候需要象
Apache
那样为指定的目录添加访问验证,一般在
Apache
下使用
htpasswd
来添加,而
htpasswd
是包含在
apache2-utils
里,一般
LNMP
一键安装包或自己编译安装
LNMP
都不会安装
apache2-utils
。
1、创建类htpasswd文件 执行下面命令:
wget -c https://www.moerats.com/usr/down/htpasswd.sh;bash htpasswd.sh
按提示输入用户名、密码、及认证文件名。脚本会自动生成认证文件。记录下脚本返回的文件路径。如:
/usr/local/nginx/conf/vpser.net.auth
。
2、为Nginx添加auth认证配置
下面是以某域名下面的
soft
目录为例,在域名的
server
段里加上如下代码:
location ^~ /soft/
auth_basic "Authorized users only";
auth_basic_user_file 这里写前面脚本返回的文件路径;
}
Authorized users only
为提示信息,可以修改成自己想让他提示的信息;
auth_basic_user_file
后面需要填
htpasswd.sh
脚本返回的人家文件的路径。按上面的提示修改好配置后,重启
nginx
,访问
http://yourdomainname/soft/
就会提示输入用户名和密码。
注意:
加上认证之后该目录下的
PHP
将不会被解析,会出现下载提示,如果想可以解析
PHP
可以将上面的配置改为:
location ^~ /soft/ {
location ~ .*\.(php|php5)?$ {
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;