To configure Laravel's TrustProxies middleware to work correctly with a Hetzner load balancer, you need to ensure that the application correctly identifies and trusts the proxy headers set by the load balancer. This is crucial for handling HTTPS requests properly and avoiding mixed content issues.
Here's a step-by-step solution:
-
Identify the IP Addresses of the Load Balancer:
- If Hetzner provides specific IP addresses or ranges for their load balancers, you should use those. If not, you can use
'*'to trust all proxies, but this is less secure.
- If Hetzner provides specific IP addresses or ranges for their load balancers, you should use those. If not, you can use
-
Configure the
TrustProxiesMiddleware:- You can continue using
'*'for development or testing purposes, but for production, it's better to specify the exact IP addresses or ranges if possible.
- You can continue using
-
Ensure Correct Headers are Used:
- The headers you've configured seem appropriate. However, ensure that the load balancer is indeed setting these headers. You might need to check Hetzner's documentation or contact their support to confirm which headers are used.
-
Update the
TrustProxies.phpFile:- If you have specific IPs, replace
'*'with an array of those IPs. Otherwise, keep it as'*'for now.
- If you have specific IPs, replace
Here's an example configuration:
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies = '*'; // Use specific IPs if available
/**
* 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_FORWARDED |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
-
Check Your Application URL Configuration:
- Ensure that your
APP_URLin the.envfile is set to usehttps://if your site is served over HTTPS. This helps Laravel generate URLs with the correct scheme.
- Ensure that your
-
Clear Configuration Cache:
- After making changes, clear the configuration cache to ensure your changes take effect:
php artisan config:cache
- After making changes, clear the configuration cache to ensure your changes take effect:
By following these steps, your Laravel application should correctly handle requests through the Hetzner load balancer, and the mixed content issue should be resolved. If problems persist, double-check the headers being sent by the load balancer and adjust the TrustProxies configuration accordingly.