All posts

Fix Load Balancer Error in Laravel

Resolve Laravel issues behind load balancers including trusted proxies, HTTPS redirect loops, and session driver configuration.

Laravel Behind a Load Balancer

Laravel provides first-class support for proxied deployments, but it must be configured. Without it, you'll face HTTPS redirect loops, wrong asset() URLs, and CSRF mismatches.

Trusted Proxies

Laravel uses the TrustProxies middleware. Configure it to trust your load balancer:

// app/Http/Middleware/TrustProxies.php
class TrustProxies extends Middleware
{
    protected $proxies = '*'; // Trust all proxies (or specify IPs)

    protected $headers =
        Request::HEADER_X_FORWARDED_FOR |
        Request::HEADER_X_FORWARDED_HOST |
        Request::HEADER_X_FORWARDED_PORT |
        Request::HEADER_X_FORWARDED_PROTO |
        Request::HEADER_X_FORWARDED_AWS_ELB;
}

Force HTTPS Properly

Don't use middleware to force HTTPS — let the load balancer handle it. But if url() and asset() generate HTTP links:

// AppServiceProvider.php
public function boot()
{
    if (config('app.env') === 'production') {
        URL::forceScheme('https');
    }
}

Session Configuration

With multiple app servers, file-based sessions break. Use Redis or database:

SESSION_DRIVER=redis
REDIS_HOST=redis-service

Health Check Route

// routes/web.php
Route::get('/healthz', function () {
    return response('ok', 200);
})->withoutMiddleware([VerifyCsrfToken::class]);

Skipping CSRF on the health route prevents the load balancer from getting 419 responses.

Bugsly captures Laravel exceptions with full request context — including the real client IP after proxy header parsing — so you can trace errors back to specific users rather than the load balancer IP.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free