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

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article