lumn+swoole+负载均衡 获取真实的客户端ip

nginx配置

server {
    listen 80;
    server_name xxxxx.xxx.com
    root /opt/onemena/wwwroot/xxxxx/project.tt.money/public;
    index index.php;

    location = /index.php {
        # Ensure that there is no such file named "not_exists"
        # in your "public" directory.
        try_files /not_exists @swoole;
    }
    # any php files must not be accessed
    #location ~* \.php$ {
    #    return 404;
    #}
    location / {
        try_files $uri $uri/ @swoole;
    }

    location @swoole {
        set $suffix "";

        if ($uri = /index.php) {
            set $suffix ?$query_string;
        }

        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        #proxy_set_header SERVER_PORT $server_port;
        #proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Real-PORT $remote_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        # IF https
        # proxy_set_header HTTPS "on";

        proxy_pass http://127.0.0.1:1215$suffix;
    }
}

php代码

protected function getClientIp($request){
        $forwarded = $request->header('X-Forwarded-For');
        $attr = explode(',',$forwarded);
        $ip = $attr[0];
        if(empty($ip)){
            $str = $request->headers;
            $reg = '|X-Forwarded-For:\s+?([^,]+)|';
            if(preg_match($reg, $str,$matches)){
                $ip = $matches[1];
            }
        }
        return  $ip;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容