Nginx基於用戶的訪問控制(Ngx_http_auth_basic_module)
官方文檔:http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html
官方示例:The ngx_http_auth_basic_module module allows limiting access to resources by validating the user name and password using the “HTTP Basic Authentication” protocol.基於HTTP,適用basic機制進行用戶認證;
Example Configuration location / { auth_basic "closed site"; auth_basic_user_file conf/htpasswd; }
Syntax: | auth_basic |
---|---|
Default: | auth_basic off; |
Context: | http , server , location , limit_except |
Syntax: | auth_basic_user_file |
---|---|
Default: | — |
Context: | http , server , location , limit_except |
Context:適用配置段
演示環境:
Server:192.168.47.140 [root@GaoServer ~]# cat /etc/redhat-release CentOS Linux release 7.2.1511 (Core) [root@GaoServer ~]# uname -r 3.10.0-327.el7.x86_64 [root@GaoServer ~]# uname -o [root@GaoServer ~]# nginx -V nginx version: nginx/1.10.2 ......
相關配置:
#httpd-tools是Apache的工具包 [root@GaoServer ~]# yum install httpd-tools -y #htpasswd命令是Apache的web服務器內置工具,用於創建和更新存儲用戶名密碼的文本文,用於HTTP用戶的basic認證 [root@GaoServer ~]# htpasswd -h htpasswd: illegal option -- h ......#常用選項: -c Create a new file. #創建一個加密文件; -n Don't update file; display results on stdout. #不更新加密文件,將加密後的賬號輸出至屏幕; -b Use the password from the command line rather than prompting for it. #在命令行中使用口令,而不是提示口令; -m Force MD5 encryption of the password (default). #MD5算法加密 -d Force CRYPT encryption of the password (8 chars max, insecure). #CRYPT算法加密 -s Force SHA encryption of the password (insecure). #SHA算法加密 -p Do not encrypt the password (plaintext, insecure). #使用明文密碼 -D Delete the specified user. #刪除指定用戶 -v Verify password for the specified user. ...... #創建一個加密文件MD5算法加密:(創建隱藏文件) [root@GaoServer ~]# htpasswd -c -m /etc/nginx/.htpasswd gning New password: Re-type new password: Adding password for user gning [root@GaoServer ~]# cat /etc/nginx/.htpasswd gning:$apr1$pTwVGCrf$BCWZFeQXXjS8Yb.JflpiL. #修改配置文件: [root@GaoServer ~]# vim /etc/nginx/conf.d/Vhost.conf server { listen 80; location /server/ { root /data/html/; auth_basic "User is"; #訪問認證輸入信息顯示給用戶; auth_basic_user_file /etc/nginx/.htpasswd; #定義使用什麼賬號文件; } } [root@GaoServer ~]# nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful [root@GaoServer ~]# nginx -s reload
訪問測試:
瀏覽器訪問IP:[Port]/server