今天开发碰到了一个问题 , 由于我的服务器是使用nginx反向代理指向hyperf的9501(127.0.0.1:9501)
但是获取到的ip都是127.0.0.1
下面就是解决方案
public function ip(){
$res = $this->request->getHeaders();
if(isset($res['http_client_ip'])){
return $res['http_client_ip'];
}elseif(isset($res['x-real-ip'])){
return $res['x-real-ip'];
}elseif(isset($res['x-forwarded-for'])){
return $res['x-forwarded-for'];
}elseif(isset($res['http_x_forwarded_for'])){
//部分CDN会获取多层代理IP,所以转成数组取第一个值
$arr = explode(',',$res['http_x_forwarded_for']);
return $arr[0];
}else{
// return $res['remote_addr'];
$serverParams = $this->request->getServerParams();
return $serverParams['remote_addr'] ?? '';
}
}
这里需要配置nginx配置文件
proxy_set_header Host $http_host; proxy_set_header Host $host;#保留代理之前的host proxy_set_header X-Real-IP $remote_addr;#保留代理之前的真实客户端ip proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr;#在多级代理的情况下,记录每次代理之前的客户端真实ip # 转发Cookie,设置 SameSite proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict"; proxy_pass http://127.0.0.1:9501;