nginx对目录进行认证

发布时间:2019-10-28编辑:脚本学堂
整理下nginx下为目录增加用户认证的配置:nginx的auth_basic认证采用与apache兼容的密码文件,因此我们需要通过apache的htpasswd生成密码文件。

整理下nginx下为目录增加用户认证的配置:nginx的auth_basic认证采用与apache兼容的密码文件,因此我们需要通过apache的htpasswd生成密码文件。
找到htpasswd文件地址。

找到htpasswd文件后,我们来创建一个用户,比如这个用户叫:test
/usr/bin/htpasswd –c /usr/local/ngnix/conf/authdb test

上面的命令在nginx的配置文件目录创建了用户为test的authdb密码文件,当然你也可以创建的在其他地方,此处nginx配置文件使用比较方便。

接着修改nginx的配置文件,在某个需要加auth_basic的server配置下添加如下内容
 

复制代码 代码如下:
location /admin/ {
auth_basic "Test Auth!";
auth_basic_user_file /usr/local/ngnix/conf/authdb;
}

最后让nginx使用最新的配置:
/usr/local/ngnix/sbin/nginx -s reload

补充一下,如果你使用了集群环境,那么还需要加Proxy_Pass:
 

复制代码 代码如下:
location /admin/ {
proxy_pass http://test.com/test/;
auth_basic "Test Auth!";
auth_basic_user_file /usr/local/ngnix/conf/authdb;
}

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

复制代码 代码如下:
location ^~ /test/ {
auth_basic "TEST-Login!";
auth_basic_user_file /opt/nginxpwd;
}

如果 不用 ^~ /test/ 而用 /test 的话 那么将只能对目录进行验证直接访问其下的文件,将不会弹出登录验证

最后nginx.conf文件如下:
 

复制代码 代码如下:
user www www;  
worker_processes  1;  
pid/var/run/nginx.pid;  
events {  
worker_connections  200;  
}  
http {  
include   mime.types;  
default_type  application/octet-stream;  
sendfileon;  
keepalive_timeout  65;  
server {  
listen   8080;  
server_name  localhost;  
charset gb2312;  
location / {  
fancyindex on;  
fancyindex_exact_size off;  
root   /data/file;  
index  index.html index.htm;  
}  
error_page   500 502 503 504  /50x.html;  
location = /50x.html {  
root   /data/nginx-dist;  
}  
location /NginxStatus {  
stub_status on;  
access_log on;  
auth_basic "NginxStatus";  
auth_basic_user_file /data/passwds;  
}  
location ^~ /test1/ {  
auth_basic "Please input your Passwords!";  
auth_basic_user_file /data/passwds;  
fancyindex on;  
fancyindex_exact_size off;  
root   /data/file;  
index  index.html index.htm;  
}  
 
location ^~ /test/ {  
auth_basic "Please input your Passwords!";  
auth_basic_user_file /data/passwds;  
fancyindex on;  
fancyindex_exact_size off;  
root   /data/file;  
index  index.html index.htm;  
}  
}  
}