Nginx的访问认证

1、设置访问认证的作用:

  在实际的工作中,有时候我们会接到给网站加密的任务,就是需要有用户名和密码才能访问网站的内容,这个一般会是在企业的内部web服务上面来实现,其实也很简单就两个参数

  语法:

location / {
    auth_basic        "closed site";
    auth_basic_user_file  conf/htpasswd;
}
  • auth_basic:语法:auth_basic string|off; 默认值:auth_basic off; 使用位置:http、server、location、limit_except
  • auth_basic_user_file:语法:auth_basic_user_file file;默认值:-;使用位置:http、server、location、limit_except (auth_basic_user_file参数后接认证密码文件)

2、设置实例:

  以www.brian.com虚拟主机为例,修改brian.conf配置文件:(添加红色标记位置)

[root@Nginx www_date]# cat brian.conf 
    server {
        listen       80;
        server_name  www.brian.com;
        location / {
            root   html/brian;
            index  index.html index.htm;
            auth_basic    "brian training";                   # 设置密码提示
            auth_basic_user_file  /opt/nginx/conf/htpasswd;   # 密码文件路径
        }
        access_log logs/brian.log main gzip buffer=128k flush=5s; 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 }

  生成认证密码文件:

[root@Nginx www_date]# yum -y install httpd          # htpasswd是Apache的命令 要安装httpd
[root@Nginx www_date]# htpasswd -bc /opt/nginx/conf/htpasswd brian brianzjz123      # 生成密码文件
Adding password for user brian
[root@Nginx www_date]# chmod 400 /opt/nginx/conf/htpasswd                 # 为了安全设置权限
[root@Nginx www_date]# chown nginx /opt/nginx/conf/htpasswd 
[root@Nginx www_date]# cat /opt/nginx/conf/htpasswd              # 查看密码文件
brian:$apr1$DMJXj4Qp$IrP.gx0wTjV6m.OBgEnNm.

  检查语法:

[root@Nginx conf]# ../sbin/nginx -t
nginx: the configuration file /opt/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx//conf/nginx.conf test is successful

  平滑重启:

[root@Nginx conf]# ../sbin/nginx -s reload

  windows浏览器测试:

  输入用户名密码:USER:brian Passwd:brianzjz123

 

posted @ 2018-03-22 18:17  Brian_Zhu  阅读(1121)  评论(0编辑  收藏  举报