Search code examples
laravellaravel-3

Laravel 3 HTTP and HTTPS routes


I have the following code:

Route::get('/',   function()
{
    return 'non secure page';
});
Route::get('/',  array('https' => true, function()
{
    return 'secure page';
}));

What I expected to happen is that these two routes would be treated differently. The first is for http://example.com requests and the second for https://example.com. Respectively, these pages should show the text 'non secure page' and 'secure page'. What actually happens is that both show the text 'secure page'. This must mean that both routes are treated the same i.e. it doesn't matter if the request was over https or http - the same route is triggered.

I know I can resolve my issue by using if (Request::secure()){ //routes }; but that then leads me to the question what use are the HTTPS secure routes in laravel? What do they achieve and when should they be used?

I've looked at the docs, but it's not clear to me what is supposed to happen.


Solution

  • The documentation says:

    When defining routes, you may use the "https" attribute to indicate that the HTTPS protocol should be used when generating a URL or Redirect to that route.

    "https" and ::secure() are only used when generating URLs to routes, they're not used to provide https-only routes. You could write a filter to protect against non-HTTPS routes (example below). Or if you want to prevent any non-HTTPS access to your entire domain then you should reconfigure your server, rather than do this in PHP.

    Route::filter('https', function() {
        if (!Request::secure()) return Response::error(404);
    });
    

    Alternative filter response:

    Route::filter('https', function() {
        if (!Request::secure()) return Redirect::to_secure(URI::current());
    });
    

    References:

    1. http://laravel.com/docs/routing#https-routes
    2. http://laravel.com/docs/routing#filters