Managing Proxy Trust in Laravel Applications

When deploying Laravel applications behind load balancers or reverse proxies, proper configuration of the TrustProxies middleware ensures correct handling of client information and HTTPS detection.

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 explore a practical example of configuring your application for various cloud environments:

<?php

use Illuminate\Http\Request;

->withMiddleware(function (Middleware $middleware) {
    // Cloud environment detection
    $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
            );
    }
});

The TrustProxies middleware ensures your application correctly handles client information when operating behind load balancers or reverse proxies.


The post Managing Proxy Trust in Laravel Applications appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.