auth_basic模块
用户认证模块,该模块可以校验用户名密码是否匹配来决定是否拒绝请求访问。
对访问目录进行加密,需要用户权限认证:这个功能特性是由ngx_http_auth_basic_module提供的,默认编译nginx时会编译好。
[root@localhost ~]# cd /usr/src/nginx-1.16.0/src/http/modules/ --该模块的.c文件
[root@localhost modules]# ll ngx_http_auth_basic_module.c
-rw-r--r-- 1 1001 1001 11642 Aug 13 2019 ngx_http_auth_basic_module.c
该模块是默认编译进Nginx的
[root@localhost ~]# cd /usr/src/nginx-1.16.0/objs/
[root@localhost objs]# cat ngx_modules.c | grep ngx_http_auth_basic --可以看到默认是编译到nginx里面去的
extern ngx_module_t ngx_http_auth_basic_module;
&ngx_http_auth_basic_module,
"ngx_http_auth_basic_module"
用户认证模块,对访问目录进行加密,需要用户权限认证,主要有以下两个指令。
Syntax: auth_basic string | off;
Default:
auth_basic off;
Context: http, server, location, limit_except
Syntax: auth_basic_user_file file;
Default: —
Context: http, server, location, limit_except
认证的配置可以在http指令块,server指令块,location指令块配置。
auth_basic string :定义认证的字符串,会通过响应报文返给客户端,也可以通过这个指令关闭认证。
auth_basic_user_file file :定义认证文件。
对指定目录加密:
location /img {
auth_basic "USER AUTH";
auth_basic_user_file /usr/local/nginx/conf/auth.passwd;
root html;
}
[root@www ]# mkdir -p /usr/local/nginx/html/img --创建这个imag目录
[root@www ]# echo "this is img html" > /usr/local/nginx/html/img/index.html --测试页面
上面是对匹配的目录img加密,如果用户输入口令,就会去找auth.passwd文件来验证口令
htpasswd命令工具
[root@localhost img]# rpm -qf /usr/bin/htpasswd --该命令由httpd-tools包提供
httpd-tools-2.4.6-90.el7.centos.x86_64
htpasswd(选项)(参数)
选项
-c:创建一个加密文件;
-m:默认采用MD5算法对密码进行加密;
-d:采用CRYPT算法对密码进行加密;
-p:不对密码进行进行加密,即明文密码;
-s:采用SHA算法对密码进行加密;
-b:在命令行中一并输入用户名和密码而不是根据提示输入密码;
-D:删除指定的用户。
[root@www nginx-1.16.1]# htpasswd -c /usr/local/nginx/conf/auth.passwd admin --生成认证文件
New password:
Re-type new password:
Adding password for user admin
访问测试一下
对首页加密:
location / {
auth_basic "User Auth";
auth_basic_user_file /usr/local/nginx/conf/auth.passwd;
}
添加用户名及密码:
[root@www]# htpasswd -b /usr/local/nginx/conf/auth.passwd test test
Adding password for user test
[root@www conf]# cat auth.passwd
admin:$apr1$t3zrmibg$UCBSzT.oXulMPWd6VByDp/
test:$apr1$a0DD/S3B$5Q7qArmJeMxSq/zTWWTpg/
[root@www]# /usr/local/nginx/sbin/nginx -s reload
可以看到,对指定的目录加密了,当我们访问img目录时,需要输入用户名及密码。它不仅可以设置访问指定目录时认证,还可以直接在访问首页时认证,如果需要关闭可以使用auth_basic off;或者直接将这两段注释掉。
输入用户名密码显示如下: