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 →
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article
PIE 1.5 Changes PHP Extension Installs in CI image

PIE 1.5 Changes PHP Extension Installs in CI

Read article
Delete Expired Sessions in Laravel With a Scheduled Command image

Delete Expired Sessions in Laravel With a Scheduled Command

Read article
Pollora: Run WordPress Inside a Laravel Application image

Pollora: Run WordPress Inside a Laravel Application

Read article
Scheduled Session Garbage Collection in Laravel 13.39 image

Scheduled Session Garbage Collection in Laravel 13.39

Read article