Search code examples
laravelamazon-web-servicesamazon-elbaws-application-load-balancer

AWS Application Load Balancer real user ip problem


I run laravel application on AWS Elasticbeanstalk, I use Application Load Balancer.

Route::get('/what-is-my-ip', function(){ 
    return request()->ip();
});

When I run this code, my ip doesn't show, it shows the load balancer's ip addresses.

Those who used the same problem with cloudflare also experienced and have solutions for cloudflare, but I couldn't find a solution for the AWS Application Load Balancer.

I am having trouble getting users' ip addresses and adding --allow-ip in maintenance mode.

function real_IP() {

    $real_IP = '';

    if (getenv('HTTP_CLIENT_IP'))
        $real_IP = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $real_IP = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $real_IP = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $real_IP = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $real_IP = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $real_IP = getenv('REMOTE_ADDR');
    else
        $real_IP = 'UNKNOWN';

    return $real_IP;
}

when i run this code it gives the correct ip address, i want to fix it across laravel.


Solution

  • You'll need to trust the AWS load balancers as a proxy.

    If you are using AWS Elastic Load Balancing, your $headers value should be Request::HEADER_X_FORWARDED_AWS_ELB. For more information on the constants that may be used in the $headers property, check out Symfony's documentation on trusting proxies.

    If you are using Amazon AWS or another "cloud" load balancer provider, you may not know the IP addresses of your actual balancers. In this case, you may use * to trust all proxies:

    protected $proxies = '*';