How to Configure Trusted Proxies In Laravel with Example

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

When running your applications behind a load balancer that terminates TLS / SSL certificates, you may notice your application sometimes does not generate HTTPS links. Typically this is because your application is being forwarded traffic from your load balancer on port 80 and does not know it should generate secure links.

How to Configure Trusted Proxies In Laravel with Example

Laravel doesn’t include configuration for this, but because it relies on Symfony for Requests and Responses you can utilize it to handle proxies.

This is where the Trusted Proxy package comes in. It handles the setup of checking the request for a trusted IP address and then allows the headers to be passed through. If it’s not from a trusted IP then it will ignore it.

Trusted Proxy takes advantage of the new Middleware feature in Laravel 5 and can be installed easily. It comes complete with a config file and a thorough documentation.

To solve , you may use the App\Http\Middleware\TrustProxies middleware that is included in your Laravel application, which allows you to quickly customize the load balancers or proxies that should be trusted by your application. Your trusted proxies should be listed as an array on the $proxies property of this middleware. In addition to configuring the trusted proxies, you may configure the proxy $headers that should be trusted:

 

<?php

namespace App\Http\Middleware;

use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var string|array
     */
    protected $proxies = [
        '192.168.1.1',
        '192.168.1.2',
    ];

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}


If you are using AWS Elastic Load Balancing, your $headers value should be Request::HEADER_X_FORWARDED_AWS_ELB. For more information on the constants that may be used in the $headers property, check out Symfony's documentation on trusting proxies.

Trusting All Proxies

If you are using Amazon AWS or another "cloud" load balancer provider, you may not know the IP addresses of your actual balancers. In this case, you may use * to trust all proxies:
 

/**
* The trusted proxies for this application.
*
* @var string|array
*/
protected $proxies = '*';

 

Related Post