How to Redirect All Requests To HTTPS in Laravel

Published on Author Code Father

Using App::before

You might be able to take advantage of the App::before() block in the app/filters.php file.

Change the block to include a simple check to see if the current request is secure, and if not, redirect it.

App::before(function($request)
{
    if(!  Request::secure())
    {
        return Redirect::secure(Request::path());}});
    

Using Filters

Another option might be to create a filter like so. People generally store this also in app/filters.php.

Route::filter('force.ssl', function()
{
    if(!  Request::secure())
    {
        return Redirect::secure(Request::path());}});
    

You can then enforce that new filter to any of your routes, route groups, or controllers like this.

Individual Route

Route::get('something', ['before' => 'force.ssl'], function()
{
    return "This will be forced SSL";});

Route Group

Route::group(['before' => 'force.ssl'], function()
{
    // Routes here.
});

Controller

You’ll need to do this in your controller’s __construct() method.

public function __construct()
{
    $this->beforeFilter('force.ssl');
}

—————————————————–/OR/——————————————————-

Another answer might be to let your web server handle this. If you are using Apache, you can use the RedirectSSL feature to make sure all requests are going to the HTTPS version of your site, and if not redirect them. This will happen before Laravel even get’s the request.

Apache RedirectSSL

If you’re on NGINX, you can accomplish this by having two server blocks. One for normal HTTPS on port 80, and another for HTTPS on port 443. Then configure the normal server block to always redirect to ssl version.

server {
    listen 80;
    server_name mydomain.com;
    rewrite ^ https://$server_name$request_uri? permanent;}


server {
    listen 443;
    server_name mydomain.com;
    ssl on;
    # other server config stuff here.
}

I’d personally go with this option as PHP itself doesn’t have to process anything. It’s generally cheaper to process a check like this at the web server level.

Comments

comments