Reputation: 46
I’m currently working on a Laravel project that is deployed behind an EC2 Load Balancer (ALB/NLB). I’m running into an issue where Laravel is not recognising the real client IP when requests pass through the load balancer. Instead, it’s returning the load balancer’s IP as the client IP.
What I’ve Tried:
protected $proxies = ['*'];
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
I can see my EC2 instance IP is being trusted but my Load Balancer's IP isn't. I have checked the X-Forwarded-For
header and it's returning the client ip correctly as the first value. I found this workaround but I want something clean where I can use $request->ip()
to fetch the client's IP address.
Workaround:
function getClientIpByRequest(Request $request): string
{
// In case of load balancer the first IP is the client IP in the X-Forwarded-For header
$clientIp = Str::before($request->header('X-Forwarded-For'), ',');
return clientIp ?: $request->ip();
}
If anyone has any ideas, what could be the issue please help. Would be really appreciated.
Upvotes: 0
Views: 32