nginx常用模块介绍之access模块

1、access模块

访问控制模块 ,该模块可以实现简单的防火墙功能,过滤特定的主机。这个模块在我们编译nginx时会默认编译进nginx的二进制文件中。

1.1、语法

Syntax: allow address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except
Syntax: deny address | CIDR | unix: | all;
Default: —
Context: http, server, location, limit_except

allow:允许访问的IP或者网段。
deny:拒绝访问的ip或者网段。
从语法上看,它允许配置在http指令块中,server指令块中还有locatio指令块中,这三者的作用域有所不同。
如果配置在http指令段中,将对所有server(虚拟主机)生效;
配置在server指令段中,对当前虚拟主机生效;
配置在location指令块中,对匹配到的目录生效。
ps: 如果server指令块,location指令块没有配置限制指令,那么将会继承http的限制指令,但是一旦配置了会覆盖http的限制指令。
或者说作用域小的配置会覆盖作用域大的配置。

1.2、http指令快配置

1.2.1、对单IP进行限制

在http指令块下配置单ip限制

http {
      include mime.types;
      default_type application/octet-stream;
      # 限制192.168.75.135这个ip访问
      deny 192.168.75.135;
      ...
}

ps: 配置完记得重载配置文件

/usr/local/nginx/sbin/nginx -s reload

在自己服务上访问

[root@localhost ~]# curl -I 192.168.75.130
HTTP/1.1 200 OK
Server: nginx/1.16.0
Date: Mon, 22 Jul 2019 02:24:19 GMT
Content-Type: text/html

在192.168.75.135机器上访问

[root@localhost ~]# curl -I 192.168.75.130
HTTP/1.1 403 Forbidden
Server: nginx/1.16.0

可以看到只对135这个ip生效了,如果有配置虚拟主机,那么这个ip将都不能访问。

1.2.2、对网段进行限制

如果想让整个网段都不能访问,只需要将这个ip改为网段即可

http {
       include mime.types;
       default_type application/octet-stream;
       # 将ip改为网段
       deny 192.168.75.0/24;
       ...
}

在自己服务器上访问

[root@localhost ~]# curl -I 192.168.75.130
HTTP/1.1 403 Forbidden
Server: nginx/1.16.0

在192.168.75.135机器上访问

可以看到都不能访问了,对整个网段的限制已生效

1.3、server指令块

配置方法都是一样的,只是作用范围不同。

1.3.1 对单IP进行限制

server {
        listen 80;
        server_name localhost;
        deny 192.168.75.135;
        ...
}

在自己服务器上访问

[root@localhost ~]# curl -I 192.168.75.130
HTTP/1.1 200 OK
Server: nginx/1.16.0
Date: Mon, 22 Jul 2019 02:45:06 GMT

在192.168.75.135机器上访问

[root@localhost ~]# curl -I 192.168.75.130
HTTP/1.1 403 Forbidden
Server: nginx/1.16.0

限制网段同上

1.4、location指令块配置

在location指令块配置访问控制。

这种配置是最多的,因为有时候我们要限制用户对某些文件或者目录的访问,这些文件通常是比较重要的或者私密的。

location /secret {
                deny 192.168.75.135;
       }
创建目录以及测试文件:
[root@localhost ~]# mkdir -p /usr/local/nginx/html/secret
[root@localhost ~]# echo "this is secret" >
/usr/local/nginx/html/secret/index.html

在本机访问

[root@localhost ~]# curl 192.168.75.130/secret/index.html
this is secret

发表评论

后才能评论