Home >Backend Development >PHP Tutorial >Managing Proxy Trust in Laravel Applications
Deploying Laravel applications behind load balancers or reverse proxies requires careful configuration of the TrustProxies
middleware to accurately manage client data and HTTPS detection. This ensures your application functions correctly in these environments.
Here's a basic example of configuring the middleware:
use Illuminate\Http\Request; // Basic proxy configuration ->withMiddleware(function (Middleware $middleware) { $middleware->trustProxies(at: [ '10.0.0.0/8', '172.16.0.0/12' ]); });
Let's examine a more robust example tailored for different cloud environments:
<?php use Illuminate\Http\Request; ?> ->withMiddleware(function (Middleware $middleware) { // Environment-specific proxy configuration $environment = env('APP_ENV'); switch ($environment) { case 'production': // AWS ELB configuration $middleware->trustProxies( at: '*', headers: Request::HEADER_X_FORWARDED_AWS_ELB ); break; case 'staging': // Digital Ocean configuration $middleware->trustProxies( at: '*', headers: Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO ); break; default: // Local/development configuration $middleware->trustProxies( at: ['127.0.0.1', '::1'], headers: Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_PROTO ); } });
This approach dynamically adjusts the TrustProxies
middleware based on the application's environment variable (APP_ENV
). This ensures accurate handling of client information regardless of whether the application runs locally, on AWS, Digital Ocean, or another platform. The correct configuration of this middleware is crucial for the reliable operation of Laravel applications deployed behind proxies.
The above is the detailed content of Managing Proxy Trust in Laravel Applications. For more information, please follow other related articles on the PHP Chinese website!