Configure Symfony or Mautic to Work Behind a AWS Elastic Load Balancer or a Reverse Proxy with HTTPS

MD Biplob Hossain
MD Biplob Hossain

What is AWS's Elastic Load Balancing?

Amazon Web Services's Elastic Load Balancing distributes incoming application traffic across multiple EC2 instances, in multiple Availability Zones. This increases the fault tolerance and performance of your applications.

The load balancer serves as a single point of contact for clients. It make balanced the user requests traffic and forward to healthy ec2 instance.

Why Need to Configure?

When you deploy your application behind AWS Elastic Load Balancer, this doesn't cause any problems with Symfony. But, when a request passes through a proxy, certain request information is sent using either the standard Forwarded header or non-standard special X-Forwarded-* headers. For example, instead of reading the REMOTE_ADDR header (which will now be the IP address of your reverse proxy), the user's true IP will be stored in a standard Forwarded: for="..." header or a non standard X-Forwarded-For header.

If you don't configure Symfony to look for these headers, you'll get incorrect information about the client's IP address, whether or not the client is connecting via HTTPS, the client's port and the hostname being requested.

 

How to Configure with Symfony?

It’s too simple. Just use the following code in web/app.php of your Symfony application. For more details you can check this demo project- 
https://github.com/symfony/symfony-demo

// web/app.php 
use Symfony\Component\HttpFoundation\Request;

$request  = Request::createFromGlobals();
Request::setTrustedProxies(array('127.0.0.1', $request->server->get('REMOTE_ADDR')));
$response = $kernel->handle($request);

 

How to Configure with Mautic?

Mautic is marketing automation software (email, social & more). 

Use the above code on index.php for Mautic version 2.3 or before. 

If you are using mautic latest version (currently 2.5.1) you don’t need to add this code. But you may get Too many redirections error   if you run your application with HTTPS. The problem is that Amazon sends different HTTPS headers than the PHP headers you look for: $_SERVER['HTTPS'] is off, while Amazon sends alternative HTTPS headers that you can use to identify that it is in fact running under HTTPS. To solve this just add this following code on your index.php

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
    $_SERVER['HTTPS'] = 'on';
}

This may work with core symfony application too. But I’ve checked only on mautic.

 

References

http://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html

http://symfony.com/doc/current/request/load_balancer_reverse_proxy.html#but-what-if-the-ip-of-my-reverse-proxy-changes-constantly

http://stackoverflow.com/questions/23621042/symfony2-behind-elb-is-redirecting-to-http-instead-of-https