Nginx-访问控制

#一、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. 访问测试

image.png

###5. 局限性

  • 用户信息依赖文件方式
  • 操作管理机械,效率低下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值