簡介
在實際工作中,企業中有些網站,要求使用賬號和密碼才能訪問,如網站后台、phpMyAdmin 、Wiki 平台 等
模塊ngx_http_auth_basic_module 允許使用“HTTP基本認證”協議驗證用戶名和密碼來限制對資源的訪問
模塊ngx_http_auth_basic_module 下有兩條指令 auth_basic 和 auth_basic_user_file
語法
auth_basic string | off;
開啟使用“HTTP基本認證”協議的用戶名密碼驗證。參數 off 可以取消繼承自上一個配置等級 auth_basic 指令的影響,默認參數為 off。
auth_basic_user_file file;
指定保存用戶名和密碼的文件,密碼是加密的,格式如下:
# comment
name1:password1
name2:password2:comment
name3:password3
可以用Apache發行包中的htpasswd命令來創建。
實戰
配置虛擬主機:
server {
listen 80;
server_name www.abc.com;
location / {
root html/blog;
index index.html index.htm;
auth_basic "xxxxxxxxxx"; # 設置用於認證的提示字符串
auth_basic_user_file /usr/local/nginx/conf/htpasswd; # 設置認證的密碼文件
}
}
生成認證文件:
yum install -y httpd # 要用到 http 的工具htpasswd 來產生賬號和密碼,所以要先安裝 http
htpasswd -bc /usr/local/nginx/conf/htpasswd abc 1234 # 設置認證的賬號密碼,會保存在密碼文件中,第一次使用要用 -bc 參數
htpasswd -b /usr/local/nginx/conf/htpasswd def 5678 # 以后使用無需加 -c 參數
chmod 400 /usr/local/nginx/conf/htpasswd
chown nginx /usr/local/nginx/conf/htpasswd
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
訪問網站提示輸入用戶名和密碼:
參考資料
http://tengine.taobao.org/nginx_docs/cn/docs/http/ngx_http_auth_basic_module.html