Record it: ban real IP based on nginx configuration

Situation

Server is in use

Task

Block IPs in specified network segments

Action

1: Method 1: Use nginx’s own deny and allow to implement

Because nginx blocked the IP of the proxy before arriving at the server, not the real IP, it failed.

2: Method 2: Add configuration


http {
    ...
    geo $ip_addr $real_ip {
        default               "";
        219.248.141.0/24      "blocked";
    }
# 首先定义了一个名为 $ip_addr 的变量,它将从客户端请求中提取出 IP 地址;
# 然后定义了一个名为 $real_ip 的变量,它将根据 $ip_addr 的值获取到对应的真实 IP 地址;
# 接着通过 geo 块对真实 IP 进行判断,如果属于 219.248.141.0/24 网段,则将其设置为字符串 "blocked",否则将其设置为默认值 "";
# 最后使用 map 块将 $real_ip 映射到一个变量 $block,如果 $real_ip 被设置为 "blocked",则将 $block 设置为 1,否则设置为 0。
    map $real_ip $block {
        default            0;
        "blocked"          1;
    }
# 在 Nginx 的主配置块中定义了一个 server 块,在这里可以通过 if 指令判断是否需要阻止访问,如果 $block 被设置为 1,则返回 HTTP 403 错误。
    server {
        ...

        if ($block) {
            return 403;
        }

        ...
    }
    ...
}

If you need to add a banned IP later, just add it in geo.

Result

Guess you like

Origin blog.csdn.net/m0_51828898/article/details/132599562