To configure different TrustProxies settings per environment in a Laravel application, you can leverage the App\Http\Middleware\TrustProxies middleware. This middleware is executed after the environment variables are loaded, allowing you to use .env variables to configure your trusted proxies.
Here's how you can achieve this:
-
Modify the
TrustProxiesMiddleware:Open the
App\Http\Middleware\TrustProxiesclass. You can customize the$proxiesproperty to use environment variables.namespace App\Http\Middleware; use Illuminate\Http\Middleware\TrustProxies as Middleware; use Illuminate\Http\Request; class TrustProxies extends Middleware { /** * The trusted proxies for this application. * * @var array|string|null */ protected $proxies; /** * The headers that should be used to detect proxies. * * @var int */ protected $headers = Request::HEADER_X_FORWARDED_ALL; public function __construct() { // Set the proxies based on the environment $this->proxies = config('trustedproxies.proxies'); } } -
Create a Configuration File:
Create a new configuration file named
trustedproxies.phpin theconfigdirectory. This file will hold the proxy settings for different environments.return [ 'proxies' => env('TRUSTED_PROXIES', null), ]; -
Set Environment Variables:
In your
.envfiles for different environments, set theTRUSTED_PROXIESvariable. You can specify a comma-separated list of IP addresses or use*to trust all proxies.For example, in your
.envfile for the production environment:TRUSTED_PROXIES=192.168.1.1,192.168.1.2And in your local
.envfile:TRUSTED_PROXIES=* -
Clear Configuration Cache:
If you have configuration caching enabled, make sure to clear the cache to apply the changes:
php artisan config:cache
By following these steps, you can configure different TrustProxies settings for each environment using environment variables, ensuring that your application correctly handles proxy headers based on the environment it is running in.