11.1 Access Based on IP Address | 基于 IP 地址访问配置

Problem

You need to control access based on the IP address of the client.

问题

需要基于客户端的 IP 地址实现访问控制功能


Solution

Use the HTTP access module to control access to protected resources:

location /admin/ {
    deny 10.0.0.1;
    allow 10.0.0.0/20;
    allow 2001:0db8::/32;
    deny all;
}

The given location block allows access from any IPv4 address in

10.0.0.0/20 except 10.0.0.1, allows access from IPv6 addresses in the

2001:0db8::/32 subnet, and returns a 403 for requests originating

from any other address. The allow and deny directives are valid

within the HTTP, server, and location contexts. Rules are checked in

sequence until a match is found for the remote address.

解决方案

使用 HTTP 的 access 模块,实现对受保护资源的访问控制:

location /admin/ {
    deny 10.0.0.1;
    allow 10.0.0.0/20;
    allow 2001:0db8::/32;
    deny all;
}

给定的 location 块级指令中配置了允许除 10.0.0.1 外的所有 10.0.0.0/20 IPv4

地址访问,同时允许 2001:0db8::/32 及其子网的 IPv6 地址访问,其它 IP 地址

的访问将会收到 HTTP 状态为 403 的响应。allow 和 deny 指令可在 HTTP、server、

location 上下文中使用。控制规则依据配置的顺序进行查找,直到匹配到控制规则。


Discussion

Protecting valuable resources and services on the internet must be

done in layers. NGINX provides the ability to be one of those layers.

The deny directive blocks access to a given context, while the allow

directive can be used to allow subsets of the blocked access. You can

use IP addresses, IPv4 or IPv6, CIDR block ranges, the keyword all,

and a Unix socket. Typically when protecting a resource, one might

allow a block of internal IP addresses and deny access from all.

结论

需要控制访问的资源需要实现分层控制。NGINX 服务器提供对资源进行分层控

制的能力。deny 指令会限制对给定上下文的访问,allow 指令与 deny 功能

相反,它们的值可以是定值 IP 地址、IPv4 或 IPv6 地址、无类别域间路由(

CIDR: Classless Inter-Domain Routing)、关键字或 UNIX 套接字。IP 限制

的常用解决方案是,允许一个内部的 IP 地址访问资源,拒绝其它所有 IP 地

址的访问来实现对资源的访问控制。

results matching ""

    No results matching ""