Nginx基于用户的访问控制(Ngx_http_auth_basic_module)
官方文档:
官方示例: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 Configurationlocation / { 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 -r3.10.0-327.el7.x86_64[root@GaoServer ~]# uname -o[root@GaoServer ~]# nginx -Vnginx version: nginx/1.10.2......
相关配置:
#httpd-tools是Apache的工具包[root@GaoServer ~]# yum install httpd-tools -y#htpasswd命令是Apache的web服务器内置工具,用于创建和更新存储用户名密码的文本文,用于HTTP用户的basic认证[root@GaoServer ~]# htpasswd -hhtpasswd: 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 gningNew 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.confserver { listen 80; location /server/ { root /data/html/; auth_basic "User is"; #访问认证输入信息显示给用户; auth_basic_user_file /etc/nginx/.htpasswd; #定义使用什么账号文件; }}[root@GaoServer ~]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@GaoServer ~]# nginx -s reload
访问测试:
浏览器访问IP:[Port]/server