yidas / client-ip
从服务器获取客户端IP,即使是在代理或负载均衡器后面也能以安全且一致的方式
1.0.0
2017-09-05 09:23 UTC
This package is auto-updated.
Last update: 2024-09-14 19:25:57 UTC
README
从服务器获取客户端IP,即使是在代理或负载均衡器后面也能以安全且一致的方式。
Web应用程序中的真实IP实现,解决了服务器在没有透明模式的情况下通过信任代理或负载均衡器接收请求的问题。
演示
echo ClientIP::get(); ClientIP::config([ 'proxyIPs' => ['192.168.0.0/16', '172.217.3.11'], 'headerKeys' => ['HTTP_X_FORWARDED_FOR'] ]); echo ClientIP::get();
如果客户端IP是203.169.1.37
,以下示例代码演示了一些连接情况
负载均衡器正常网络
你的服务器位于负载均衡器后面,并处于私有网络中。
ClientIP::config([ 'proxyIPs' => true ]);
将proxyIPs
设置为true
表示所有请求都通过负载均衡器,这将始终获取转发IP,与上述设置相同
ClientIP::config([ 'proxyIPs' => ['0.0.0.0/32'] ]);
服务器返回的结果
192.168.0.10 //Before setting the config
203.169.1.37 //After setting the config, get the forward IP
代理可选网络
如果你的服务器位于公共网络中,不仅可以直接接收请求,还支持通过信任代理进行访问
ClientIP::config([ 'proxyIPs' => ['172.217.3.11'] ]);
服务器返回的结果
- 方法1:客户端直接连接到服务器
203.169.1.37 //Before setting the config
203.169.1.37 //The request IP is not from proxyIPs, so identify as a Client.
- 方法2:客户端通过代理连接到服务器
172.217.3.11 //Before setting the config
203.169.1.37 //The request IP comes from proxyIPs, get the forward IP.
安装
在你的项目中运行Composer
composer require yidas/client-ip
然后在应用的引导阶段初始化它,例如在config
文件中
require __DIR__ . '/vendor/autoload.php'; ClientIP::config([ 'proxyIPs' => ['192.168.0.0/16'] ]);
配置
示例配置
ClientIP::config([ 'proxyIPs' => ['192.168.0.0/16', '172.217.2.89'], 'headerKeys' => ['HTTP_X_FORWARDED_FOR'], ]);
讨论
从Web服务器实现
获取真实IP的另一种方式是从Web服务器端实现