nginx 通过用户名密码认证控制访问web页面

nginx控制用户访问主要有三种方法:1:通过IP限制(配置allow和deny,属于ngx_http_access_module模块,配置段http, server, location, limit_except); 2、通过用户名密码限制(配置auth_basic和auth_basic_user_file,属于ngx_http_auth_basic_module模块,配置段http, server, location, limit_except );3、两种方法同时用。4、限制IP地址段(配置Geo,本文不配)

2.修改 nginx 配置文件

pid nginx.pid;
worker_processes  1;

events {
        use epoll;
        worker_connections 65535;
        }

http{
gzip on;
gzip_min_length 1000;
......
server {
   listen 80;
   server_name  localhost;
   .......
   #新增下面两行
   auth_basic "Please input password"; #这里是验证时的提示信息 
   auth_basic_user_file /usr/local/src/nginx/passwd;
   location /{
   deny  192.168.1.1;
   allow 192.168.1.0/24;
   allow 10.1.1.0/16;
   allow 2001:0db8::/32;
   deny  all;
   .......
   }
   }
}

上面将配置auth_basic和auth_basic_user_file放在server中,是对整个站点开启验证。若果要对部分开启验证,要凡在要验证的location中。allow和deny是按从上到下的顺序,类似iptables,匹配到了便跳出。如上的例子先禁止了192.16.1.1,接下来允许了3个网段,其中包含了一个ipv6,最后未匹配的IP全部禁止访问.  在实际生产环境中,我们也会使用nginx 的geo模块配合使用(http://www.ttlsa.com/nginx/using-nginx-geo-method/)。

生成密码

可以使用htpasswd,或者使用openssl

方法一、使用openssl

#账号:super  密码:123456
printf "peter:$(openssl passwd -crypt 123456)\n" >>conf/htpasswd
cat conf/htpasswd

#输出super:xyJkVhXGAZ8tM

方法一、使用htpasswd

yum  -y install httpd-tools
#或yum install -y httpd
#两者都包含htpasswd工具
htpasswd -c /etc/nginx/passwd.db super
pkill -9 nginx
/usr/sbin/nginx  -c /etc/nginx/test1.conf

注意:上面的 /etc/nginx/passwd.db是生成密码文件的路径,然后super是用户名,你可以根据需要自行设置成其它用户名。运行命令后,会要求你连续输入两次密码。输入成功后,会提示已经为super这个用户添加了密码。

nginx -t        #检查语法是否错误
nginx -s reload   #配置文件热加载
nginx -c /etc/nginx/test.conf    #手动指定配置文件

#sudo nginx #打开 nginx
#nginx -s reload|reopen|stop|quit  #重新加载配置(reload)|重启(reopen)|停止(stop)|退出(quit) nginx

pkill -9 nginx   #强制杀掉nginx进程

猜你喜欢

转载自blog.csdn.net/qq_23587541/article/details/86038543