在實際工做中,企業中有些網站,要求使用帳號和密碼才能訪問,如網站後臺、phpMyAdmin 、Wiki 平臺 等php
模塊ngx_http_auth_basic_module 容許使用「HTTP基本認證」協議驗證用戶名和密碼來限制對資源的訪問html
模塊ngx_http_auth_basic_module 下有兩條指令 auth_basic 和 auth_basic_user_filenginx
auth_basic string | off;
開啓使用「HTTP基本認證」協議的用戶名密碼驗證。參數 off 能夠取消繼承自上一個配置等級 auth_basic 指令的影響,默認參數爲 off。vim
auth_basic_user_file file;
指定保存用戶名和密碼的文件,密碼是加密的,格式以下:工具
# comment name1:password1 name2:password2:comment name3:password3
能夠用Apache發行包中的htpasswd命令來建立。網站
配置虛擬主機:ui
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
訪問網站提示輸入用戶名和密碼:
spa
http://tengine.taobao.org/nginx_docs/cn/docs/http/ngx_http_auth_basic_module.htmlcode