Symfony2 behind ELB is redirecting to http instead of https Symfony2 behind ELB is redirecting to http instead of https symfony symfony

Symfony2 behind ELB is redirecting to http instead of https


Take a look at

vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Request.php

AWS ELB's use HTTP_X_FORWARDED_PROTO and HTTP_X_FORWARDED_PORT while Symfony looks the X_FORWARDED_PROTO and X_FORWARDED_PORT headers to judge the connection and its secure status.

You can try changing those keys in the trustedHeaders although I would not recommend directly changing them but finding a way to override those.

protected static $trustedHeaders = array(        self::HEADER_CLIENT_IP    => 'X_FORWARDED_FOR',        self::HEADER_CLIENT_HOST  => 'X_FORWARDED_HOST',        self::HEADER_CLIENT_PROTO => 'HTTP_X_FORWARDED_PROTO',        self::HEADER_CLIENT_PORT  => 'HTTP_X_FORWARDED_PORT',    );

Reference - http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-for


  1. Make sure that trusted_hosts and trusted_proxies configuration properties are set appropriately.
  2. Make sure that your load balancer adds X-Forwarded-For, X-Forwarded-Host, X-Forwarded-Port and, what's most important, X-Forwarded-Proto headers to the HTTP request send to the application.

Documentation: Trusting Proxies.


EDIT:

As @A23 suggested you should also check if ELB is using "standard" headers names. If not, change them using one of following:

Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X-Proxy-For');Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X-Proxy-Host');Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X-Proxy-Port');Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X-Proxy-Proto');


I had the exact same problem with a PHP application using AWS and ELB with SSL in a CakePHP application.

My solution was good in some ways and bad in others. The problem was 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:

$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'

I worked out that my base URL constant that Cake defined internally had the http protocol in it, so I simply redefined the $_SERVER['HTTPS'] variable on the very first line of my index.php file in Cake - and I wouldn't be surprised if you could do the same in symfony):

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

This allowed my application to continue on, detect HTTPS as being 'on' as would normally be expected and allow Cake to internally manage the protocol in my base URL constant.

Good:

  • fixed the problem immediately
  • used 3 lines of code

Bad:

  • whenever I upgrade my Cake core, I'll have to put this back in again