It's a common practice to deploy Laravel apps behind load balancers, aka proxy.
But doing this requires you to change the middleware settings so Laravel trusts your load balancer.
If you don't change it, some side effects may occur, such as hitting rate limiters on for all users at once instead of per IP address.
In your bootstrap/app.php file, you need to add the following inside the ->withMiddleware function.
$middleware->trustProxies(at: '*')
The asterisk * will trust any load balancer.
Please note that it's recommended to narrow down the allowed proxies, because any user can tamper with the header used to determine the real user IP.
If you only have one load balancer and you know the IP address, you can set the IP address like this:
$middleware->trustProxies(at: '10.0.0.2')
If you have multiple load balancers, you can provide an array.
$middleware->trustProxies(at: [
'10.0.0.2',
'10.0.1.2',
])
Or even a CIDR for the IP addresses.
$middleware->trustProxies(at: '10.0.0.0/8')
In some cases, the load balancer adds its IP address to the right side of the X-Forwarded-For standard header, maintaining the leftmost IP address as the actual user IP.
To ensure Laravel obtains the correct IP address for the user's IP, you may need to set it to 0.0.0.0/0, allowing any load balancer to discard all IP addresses in this header except the leftmost one.
Top comments (0)