您当前的位置: 首页 >  nginx

苗先生的PHP记录

暂无认证

  • 0浏览

    0关注

    190博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

hyperf通过nginx代理后, 获取真实ip

苗先生的PHP记录 发布时间:2022-09-09 15:06:04 ,浏览量:0

 今天开发碰到了一个问题 , 由于我的服务器是使用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; 

关注
打赏
1665468453
查看更多评论
立即登录/注册

微信扫码登录

0.0352s