如果您使用nginx代理,
首先添加代理配置
location / {
# proxy host and ip information
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy
proxy_pass http://xx.xx.xx.xx:xxxx;
}
然后您可以通过请求 header 中的【X-Real-IP】值来生成真实IP。
这样应该也可以:
location ^~ /lgbhf/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://127.0.0.1:9501/lgbhf/;
}
代码中这么写:
$headers = array_map(function($value) {
return $value[0];
}, $this->request->getHeaders());//获取headers信息
// 获取客户端的真实 IP
$clientIp = $headers['x-real-ip'] ?? '';
2.### hyperf框架获取客户端真实ip
具体看公司nginx代理的配置,如果request->getHeaders();
use Hyperf\Utils\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;
function getRealIp(): string
{
$request = ApplicationContext::getContainer()->get(RequestInterface::class);
$headers = $request->getHeaders();
if(isset($headers['x-forwarded-for'][0]) && !empty($headers['x-forwarded-for'][0])) {
return $headers['x-forwarded-for'][0];
} elseif (isset($headers['x-real-ip'][0]) && !empty($headers['x-real-ip'][0])) {
return $headers['x-real-ip'][0];
}
$serverParams = $request->getServerParams();
return $serverParams['remote_addr'] ?? '';
}