How to deal with SSL in Laravel?

June 16, 2014 at 6:31 am

SSLAs you probably already know, Laravel has a lot of flexibility around “routes” and even more so if you combine it with “filters“. The easiest way to deal with SSL in Laravel is using filters. As apposed to struggling with .htaccess or doing it some other way in code. I created the following two filters and this solved the problem for me:

    Route::filter('force.ssl', function()
    {
        if( ! Request::secure())
        {
            return
                Redirect::secure(
                    Request::path().(empty($_SERVER['QUERY_STRING']) ? '' : '?'.$_SERVER['QUERY_STRING'])
                );
        }
    });

    Route::filter('no.ssl', function()
    {
        if( Request::secure())
        {
            return Redirect::to(
                Request::path().(empty($_SERVER['QUERY_STRING']) ? '' : '?'.$_SERVER['QUERY_STRING']), 302, array(), false
        );
    }
});

You can then use it like this:

Route::group(array('before' => 'no.ssl'), function()
{
    Route::resource('/', 'SiteController');
});

I’m sure the “QUERY_STRING” part could probably be replaced with a more Laravel-y way of doing this, but this worked for me.