为Nginx添加basic_auth,意思就是访问页面的时候需要弹出来一个用户和密码验证的东西,本文基于CentOS 6
1, 安装密码生成工具htpasswd并生成用户密码文件
yum install httpd-tools #适用centos sudo apt-get install apache2-utils #适用ubuntu
生成用户密码文件
$ htpasswd -c /var/www/html/.htpasswd user1 #回车会要求输入两遍密码,会清除所有用户! $ htpasswd -bc /var/www/html/.htpasswd user1 password #不用回车,直接指定user1的密码为password $ htpasswd -b /var/www/html/.htpasswd user2 password #添加一个用户,如果用户已存在,则是修改密码 $ htpasswd -D /var/www/html/.htpasswd user2 #删除用户
2, 为Nginx添加basic_auth配置
server {
listen 80;
# root /tmp;
# index index.html index.htm;
server_name zhukun.net www.zhukun.net;
location / {
auth_basic "input you user name and password";
auth_basic_user_file /export/servers/.htpasswd;
proxy_pass http://127.0.0.1:9000;
}
}
然后再次访问zhukun.net时便会弹出验证框要求输入用户名和密码。
3, 可能遇到的问题
访问zhukun.net没有弹出验证框怎么办?
首先修改nginx.conf,将日志级别调为info,如下
$ cat /export/servers/nginx-1.12.1/conf/nginx.conf
.......
user admin;
worker_processes 8;
error_log logs/error.log info;
......
然后再次访问让其产error_log
看到error_log时会发现有如下错误产生
*69 no user/password was provided for basic authentication, client: 10.12.138.126, server: www.zhukun.net, request: "GET /date_lateral HTTP/1.1", host: "www.zhukun.net"
原因在于
The HTTP Basic authentication works as following: *) A browser requests a page without user/password. *) A server response with 401 page, sending realm as well. At this stage the 401 code appears in access_log and the message “no user/password …” appears in error_log. *) The browser shows a realm/login/password prompt. *) If a user will press cancel, then the browser will show the received 401 page. *) If the user enters login/password, then the browser repeats the request with login/password. Then until you will exit the browser, it will send these login/password with all requests in protected hierarchy.
error_page配置的401页面不存在或者指向问题导致的,可以注释掉401配置或者保证401配置指向的文件可用,然后basic_auth便会生效。