Request Component userIp behind Load Balancer

Hi there, we often have the situation where the userIP address is not correctly forwarded to the Yii::$app->request->userIp method. There are a few configuration options available in yii\web\Request. I also found a few GitHub issues around this topic but i want to have a forum post to make it clear and maybe help others struggling as well.

In our example we are using DigitalOceans App Platform. So the app is running behind an unknown load balancer ip and the user ip is provided in a variable called HTTP_DO_CONNECTING_IP. So i came up with the following solution:

'request' => [
    'class' => 'yii\web\Request',
    'ipHeaders' => ['HTTP_DO_CONNECTING_IP'],
    'trustedHosts' => [
        $_SERVER['REMOTE_ADDR'],
    ]
]);

Is there a better solution for that problem or is this the “best practice” solution? As mentioned, we do not know the load balancer IP, therefore using $_SERVER['REMOTE_ADDR'].

1 Like

That looks OK if you’re 100% sure that noone can connect to the host directly.

Worth posting it into wiki as well https://www.yiiframework.com/wiki

If this happens, exposing the remote addr and the users IP is the smallest problem, i would say. Or what do you exactly mean by connect to the host?

No, I mean original host IP i.e. end user -> proxy -> host is OK but end user -> host is not OK because host will trust $_SERVER['REMOTE_ADDR'] and in this case it’s user’s IP. User will be able to spoof IP via sending HTTP_DO_CONNECTING_IP header.