July 10, 2017

Application Prep

We see how load balancing affects our application and how to ensure our Laravel app generates correct URIs, routes, redirects, and more.

Let's see what our applications see when they receive an HTTP request. We'll discover we have some loose ends to tie up.

Testing our Application

We'll dump out $_SERVER and some other information and see what we get. Edit file routes/web.php:

Route::get(/, function() {
    dd(
        $_SERVER,
        request()->getHost(),
        request()->getClientIps(),
        redirect('/somewhere')->getTargetUrl(),
        url('/somewhere'),
        action('HomeController@index')
    );
});

The results of these aren't exactly what we want - Laravel doesn't know we have a load balancer, and thus generates links (etc) incorrectly!

We need to make Laravel aware of our proxy (the load balancer), otherwise it will ignore the X-Forwarded-* headers. When it becomes aware of them, it will use them to generate correct links and use the correct protocols.

Trusted Proxy

Laravel 5.5 comes with the TrustedProxy package which does this for us (you can pull it into your older Laravel projects if you're not on 5.5).

When Laravel 5.5 is released, it will auto-load the service provider. For now, we need to update config/app.php to add the Fideloper\Proxy\TrustedProxyServiceProvider item.

We simply setup the configuration:

sudo -u www-data php artisan vendor:publish

Once we create the config/trustedproxy.php file, we can set our load balancer as trusted.

return [
    'proxies' => [
        '172.31.10.88',
    ],

    # Some other things omitted

];

And then we can set the IP address of our trusted proxy (the load balancer) is using.

Or we can use a wildcard if we won't know the IP address, which is the case when using a load balancer service such as ELB, ALB, Linode's equivalent and others.

Once that's set, we should see Laravel work correctly!

All Topics