Hello @victor-sudakov
If I see: https://laravel.com/docs/10.x/requests#configuring-trusted-proxies it could be possible that you add a different proxy address. That does maybe help, else I think that you need to dive in the TrustedProxy to see what you need to change.
See the code online: https://github.com/laravel/framework/blob/10.x/src/Illuminate/Http/Middleware/TrustProxies.php
Hello @tvbeek
Thanks for the link. Seems the value of $headers
should be modified to solve my problem, but I'm not sure if $headers
is only used to detect a proxy or to actually retrieve the client's IP address? The question is how and where I should modify the list of trusted header names in my code? Is there an example?
The TrustedProxies middleware in Laravel only respects the X-Forwarded-* headers by default, but you can customize this behavior to use the X-Real-IP header instead.
To do this, you need to create a custom TrustedProxies middleware and override the setTrustedProxyIpAddresses method to include the X-Real-IP header. Here's an example of how to do this:
Create a new middleware class by running the following command in your terminal: php artisan make:middleware CustomTrustedProxies
Open the CustomTrustedProxies middleware file located in the app/Http/Middleware directory.
Add the following code to the top of the file to import the necessary classes: use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\IpUtils;
Override the setTrustedProxyIpAddresses method to include the X-Real-IP header. Here's an example of how to do this: protected function setTrustedProxyIpAddresses(Request $request) { $ipAddresses = $this->getConfiguredProxyIpAddresses();
// Add X-Real-IP header to trusted proxies $xRealIp = $request->header('X-Real-IP'); if (!empty($xRealIp) && IpUtils::checkIp($xRealIp, $ipAddresses)) { $ipAddresses[] = $xRealIp; }
// Only trust the IP addresses in the array $request->setTrustedProxies($ipAddresses, $this->getTrustedHeaderNames()); } This code checks if the X-Real-IP header is present in the request and if it matches one of the configured proxy IP addresses. If it does, it adds the X-Real-IP header to the array of trusted proxy IP addresses. Finally, it calls the setTrustedProxies method on the request object to set the trusted proxies.
Register the custom middleware in your App\Http\Kernel file by adding the following line to the $middleware array: \App\Http\Middleware\CustomTrustedProxies::class, Make sure to add it after the Illuminate\Http\Middleware\TrustProxies middleware.
That's it! Your Laravel application should now trust the X-Real-IP header as a valid proxy IP address.
victor-sudakov, tvbeek liked this reply
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community