Laravel Tutorials

Managing Proxy Trust in Laravel Applications

Published
Managing Proxy Trust in Laravel Applications image

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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article
Laranon: Reversible PII Anonymization for Laravel and LLMs image

Laranon: Reversible PII Anonymization for Laravel and LLMs

Read article
PHP 8.6 is released!  image

PHP 8.6 is released!

Read article
Laravel Warrant: Row-Level Permissions With Eloquent image

Laravel Warrant: Row-Level Permissions With Eloquent

Read article
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article