hyperf: 部署在nginx后面,并获取到真实ip

一,配置nginx

官方文档地址:

https://hyperf.wiki/3.1/#/zh-cn/tutorial/nginx

配置文件:

/etc/nginx/site-enabled/hyperf.conf

upstream hyperf {
    # Hyperf HTTP Server 的 IP 及 端口
    server 127.0.0.1:9501;
    # server 127.0.0.1:9502;
}

server {
        listen       380;
        server_name  localhost;

        access_log   /data/logs/nginxlogs/hyperf-access.log;
        error_log    /data/logs/nginxlogs/hyperf-error.log;

        location / {
            # 将客户端的 Host 和 IP 信息一并转发到对应节点  
            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;
        
            # 转发Cookie,设置 SameSite
            proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";
        
            # 执行代理访问真实服务器
            proxy_pass http://hyperf;
        }

    }

 

二,后端hyperf中获取真实ip

controller/ImageController.php

    public function imagedetail(RequestInterface $request, ResponseInterface $response) {

        echo "\nip:\n";
        echo "remote_addr:".$request->getServerParams()['remote_addr']."\n";
        echo "X-Real-IP:".$request->getHeaderLine('X-Real-IP')."\n";

        $ip = get_client_ip();
        echo "final:".$ip."\n";
        $data = [
            'ip' => $ip,
        ];
        return $response->json($data);

    }

app/Functions.php

if (! function_exists('get_client_ip')) {
    /**
     * 获取客户端 ip
     *
     * @return mixed|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    function get_client_ip(): string
    {
        $request = request();
        return $request->getHeaderLine('X-Forwarded-For')
            ?: $request->getHeaderLine('X-Real-IP')
                ?: ($request->getServerParams()['remote_addr'] ?? '')
                    ?: '127.0.0.1';
    }
}

三,测试效果

控制台:

ip:
remote_addr:127.0.0.1
X-Real-IP:192.168.219.1
final:192.168.219.1

 

posted @ 2025-02-15 11:07  刘宏缔的架构森林  阅读(180)  评论(0)    收藏  举报