Loading... ## 方法1:使用 ngx_http_geo_module 模块 官方文档:https://nginx.org/en/docs/http/ngx_http_geo_module.html > 语法: `geo [$address] $variable { ... }` > 默认值: `—` > 段: `http` 在 http 段中配置一个 IP 范围,例如: ``` geo $whitelistip { # whitelistip 为变量名,可以自定义 default 0; # 默认值,将变量 $whitelistip 设置为0 11.22.33.0/24 1; # 白名单IP段,将变量 $whitelistip 设置为1 172.99.99.0/24 1; # 白名单IP段,将变量 $whitelistip 设置为1 10.77.77.0/24 1; # 白名单IP段,将变量 $whitelistip 设置为1 } ``` 在 server 段中配置: ``` if ( $whitelistip = 0 ) { return 403; } ``` `$whitelistip` 这个变量值如果为 `0` ,则表示访问站点的客户端 IP 不在白名单中,不能访问站点,会返回403错误。 这里的 `return 403;` 也可以修改成其他的,比如 302 跳转 `return 302 https://www.google.com;` 配置禁止访问后,重载配置文件生效。 ### 使用 proxy_protocol 时,获取到的 IP 为 127.0.0.1 怎么解决? 改从 `$proxy_protocol_addr` 获取客户端 IP 地址即可,原先默认会从 `$remote_addr` 变量获取。 ``` geo $proxy_protocol_addr $whitelistip { # 在变量前增加 $proxy_protocol_addr default 0; 11.22.33.0/24 1; 172.99.99.0/24 1; 10.77.77.0/24 1; } ``` ## 方法2:使用 ngx_http_access_module 模块 官方文档:https://nginx.org/en/docs/http/ngx_http_access_module.html > 语法: `allow/deny address | CIDR | unix: | all;` > 默认值: `—` > 段: `http, server, location, limit_except` 在 http、server、location 段中配置都可: ``` location / { deny 192.168.1.1; # 禁止 192.168.1.1 访问路径 / allow 192.168.1.0/24; # 允许 192.168.1.0/24 访问路径 / allow 10.1.1.0/16; # 允许 10.1.1.0/16 访问路径 / deny all; # 除了上面允许的IP,其他都禁止访问 } ``` 配置禁止访问后,重载配置文件生效,使用禁止的IP访问站点会返回 403 最后修改:2024 年 03 月 05 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏