#一、nginx 访问控制模块
- 基于IP的访问控制:
http_access_module
- 基于用户的信任登录:
http_auth_basic_module
#二、基于IP的访问控制
###1. 配置语法
Syntax:allow address | CIDR | unix: | all;
default:默认无
Context:http,server,location
Syntax:deny address | CIDR | unix: | all;
default:默认无
Context:http,server,location
###2. 配置测试
server {
listen 80;
server_name localhost;
location ~ ^/admin {
root /usr/share/nginx;
index index.html;
deny 192.168.181.128;
allow all;
}
}
#需要注意:
如果先允许访问,在定义拒绝访问。那么拒绝访问不生效。
虚拟机宿主机IP为192.168.181.128
,虚拟机IP为192.168.181.131
,故这里禁止宿主机访问,允许其他所有IP访问。
[root@localhost ~]# curl -I 192.168.181.131/admin
HTTP/1.1 403 Forbidden
Server: nginx/1.16.1
Date: Thu, 12 Mar 2020 10:40:24 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive
宿主机访问http://192.168.1.11/admin
,显示403 Forbidden
。
当然也可以反向配置,同时也可以使用IP网段的配置方式,如allow 192.168.1.0/24;
,表示满足此网段的IP都可以访问。
###3. 指定location
拒绝所有请求
如果你想拒绝某个指定URL地址的所有请求,而不是仅仅对其限速,只需要在location
块中配置deny
all指令:
server {
listen 80;
server_name localhost;
location /admin {
root /usr/share/nginx;
index index.html;
deny all;
}
}
#三、基于用户的信任登录
###1. 配置语法
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
file:存储用户名密码信息的文件。
###2. 配置示例
server {
listen 80;
server_name localhost;
location ~ ^/admin {
root /usr/share/nginx;
index index.html;
auth_basic "Auth access test!";
auth_basic_user_file /etc/nginx/user_pass;
}
}
auth_basic
不为off
,开启登录验证功能,auth_basic_user_file
加载账号密码文件。
###3. 建立口令文件
# htpasswd 是开源 http 服务器 apache httpd 的一个命令工具,用于生成 http 基本认证的密码文件
[root@localhost ~]# yum -y install httpd-tools
# 第一次创建用户加 c 参数
[root@localhost ~]# htpasswd -cm /etc/nginx/user_pass chen
New password:
Re-type new password:
Adding password for user chen
# m 参数是密码MD5加密
[root@localhost ~]# htpasswd -m /etc/nginx/user_pass chao
New password:
Re-type new password:
Adding password for user chao
[root@localhost ~]# cat /etc/nginx/user_pass
chen:$apr1$oMej1ywj$X5Cr8s/TppazF/5PjCM261
chao:$apr1$Xnr9boZc$y1lYq5U4Hn.tUx2VHCOsh/
###4. 访问测试
###5. 局限性
- 用户信息依赖文件方式
- 操作管理机械,效率低下