Nginx访问控制

1、基于地址访问控制

1)安装模块

所需模块默认已经内置,无需再次安装

2)命令

allow:
语法:   allow address | CIDR | unix: | all;
默认值:配置段:   http, server, location, limit_except

allow解释:允许某个IP或者IP网段访问

deny:
语法:   deny address | CIDR | unix: | all;
默认值:配置段:   http, server, location, limit_except

deny解释:禁止某个IP或者IP网段访问

3)实验演示

①要求

限制主机192.168.25.136访问web1.test.com,其余同网段192.168.25.0/24其它主机均可访问web1.test.com,拒绝其它所有主机访问web1.test.com

②实验环境

服务端:192.168.25.137 web1.test.com
客户端:192.168.25.136 & 192.168.25.138

③修改配置文件

server {
listen  80;  
server_name  web1.test.com;
location / {
    autoindex on;
    root   /usr/share/nginx/html/web1;
    index  index.html index.htm;
    deny   192.168.25.136;
    allow  192.168.25.0/24;
    deny   all;
        }
}

注意:从上到下的顺序,类似iptables & ACL,一旦匹配立即跳出

④重启nginx

[root@www ~]# systemctl restart nginx

⑤客户端测试

[root@136 ~]# curl web1.test.com
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@138 ~]# curl web1.test.com
this is web1 test page

2、基于用户访问控制

1)安装模块

对于实现访问网站或目录密码认证保护,nginx的HTTP基本认证模块(HTTP Auth Basic)可以实现。这个模块提供基于用户名与密码的验证保护站点或站点的一部分。

HTTP基本认证模块默认已经内置,无需再次安装

2)命令

auth_basic:
语法:   auth_basic  string | off;
默认值:

auth_basic解释:指令包含一个具有测试用户名和密码的HTTP基本认证,指定的参数将用于认证域。如果将该值设置为“off”则忽略下级指令继承的动作。

auth_basic_user_file:
语法:   auth_basic_user_file  file;
默认值:

auth_basic_user_file解释:指令为验证域指定了密码文件的路径,0.6.7版本以后这里指定的文件是nginx.conf所在目录的相对路径,而不是prefix指定的路径。上方指定的 string(自定义字符串) 所代表单词将会出现在第一次访问Nginx站点的弹出框内。
注意:最后的路径避免麻烦可以直接用绝对路径,如果需要使用相对路径,需要写在当前配置文件所在路径的基础上。

3)实验演示

①要求

所有主机访问web1.test.com均需要进行身份验证(输入账号 & 密码)。

②实验环境

服务端:192.168.25.137 web1.test.com
客户端:192.168.25.136 & 192.168.25.138

③修改配置文件

server {
listen  80;
server_name  web1.test.com;
location / {
    autoindex on;
    root   /usr/share/nginx/html/web1;
    index  index.html index.htm;
    auth_basic "Restricted";
    auth_basic_user_file /usr/share/nginx/webuserpass;
        }
}

④创建账号密码

[root@www ~]# htpasswd -c /usr/share/nginx/webuserpass tom		//tom用户(无需事先创建)
New password: 							//密码:redhat
Re-type new password: 					//确认密码:redhat
Adding password for user tom

⑤重启nginx

[root@www ~]# systemctl restart nginx

⑥客户端测试(浏览器测试)

[root@136 ~]# elinks web1.test.com
[root@138 ~]# elinks web1.test.com

192.168.25.136
在这里插入图片描述
在这里插入图片描述
192.168.25.138
在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值