Search code examples
laravelapacheproxyload-balancing

How to get visitors remote IP behind a load balancer and Cloudflare and have the remote IP also available to Apache


I'm not entirely sure how to word this question as eloquently as it could be so please be gentle with me.

We currently have 2 Apache/Nginx/Plesk Web Server VM's that are behind a Network Load Balancer. The domain to the site on those VM's is proxied via Cloudflare.

The site is built with Laravel.

First of all Laravel wasn't retrieving the correct remote IP address of the visitor so within app/Http/Middleware/TrustProxies.php the following was added. (I know there are packages that can be used instead of this but for now this is what is being used)

protected $proxies = '*';

The correct IP was then available.

We then have a problem have a problem where Apache logs have the remote IP listed as 10.7.224.225 which I believe is the internal IP for the Network Load Balancer (IONOS). remoteip_module is installed so I added below via Plesk as additional directives.

RemoteIPHeader CF-connecting-IP

The Apache logs then start populating with the correct remote IP address however Laravel then stops reporting the correct IP address and records 10.7.224.225 instead.

It's a bit like going round in circles. Anyone else been faced with similar? What did you do?

Update:

Since posting, I've been looking into this more. I dumped $_SERVER and can see that HEADER_X_FORWARDED_FOR contains 2 comma separated IP addresses (which is what the header is designed to do) and in these cases the leftmost IP is the correct IP and any others will be proxy IP's. Laravel is returning the rightmost IP as the IP instead of the leftmost, does anyone know why or how to return the correct leftmost IP address?


Solution

  • For anyone else that experiences this issue, I resolved this by installing Trust Cloudflare's Proxies for Laravel https://github.com/monicahq/laravel-cloudflare from Github.

    It generates a list of Cloudflare IP's and when Cloudflare IP's are detected they're used as trusted proxies. It has a command scheduled in console.php so make sure to add it to your cron.