Laravel 5 : SSL routes behind a load balancer

I just recently ran into an interesting problem when working on a Laravel website tucked away behing a loadbalancer on an Apache webserver. Though the website was using ssl, every url generated by Laravel had http:// as protocol instead of https://. Apparently the $_SERVER variables indicate it’s not ssl, except for $_SERVER[‘HTTP_X_FORWARDED_PROTO’] which is not used by Laravel to detect wether ssl is on or not.

I was looking for a proper way to solve this issue because multiple classes and functions generate urls, like for example the helper functions ‘route’ and ‘url_to’ but als the Form-class with Form::open(). So overriding all these classes and functions was not a very smooth nor adequate solution.

I did some digging to figure out how to solve this problem and this is what I came up with :

The ssl detection is handled by \Illuminate\Http\Request::isSecure. The trick is to override this method and have Laravel use this override.

First create a custom Request class that extends this class:

I found the code in this method on stackoverflow.com. I just added two lines and there wasn’t any real reason to change any of it.

Now have Laravel use this class instead of  \Illuminate\Http\Request:

In /public/index.php comment out the following line:

Now replace that line with the following:

Your code will now look like this:

Of course you can replace the \Custom\Http namespace with your own namespace.

I would have prefered having Laravel use an Alias instead of solving it this way but because it’s not a very dramatic code change I was quite happy settling for this solution. I’m also not sure using an alias is actually possible as Illuminate\Http\Request is implicitly called in index.php.

That’s all folks!

 

 

Published by

Justin

Justin

Hi there! I'm a software engineer currently employed at a company in The Hague in the Netherlands. You can find out more about me and my qualifications on LinkedIn (http://nl.linkedin.com/pub/justin-van-schaick/26/1b0/210). I started this blog in order to share interesting code snippets and tutorials on mainly Javascript, PHP and related frameworks. The internet is an invaluable resource for programmers and unfortunately there's never enough documentation out there. So this is me trying to contribute to that.

Leave a Reply