Laravel 5 - Redirect to HTTPS

1

Working on my first Laravel 5 project, I'm not sure where or how to translate the logic to force a redirect to the HTTPS protocol in my application. The key point here is that there are many domains pointing to my application and only two of three use SSL (the third resort to another domain, it's a long story). So, I would like to handle this situation in the application logic instead of editing the .htacces file.

In Laravel 4.2 I was able to complete the redirection with this code, added in the file filters.php

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

I'm thinking that a Middleware class where I think something like the above should be implemented, but I can not figure out how.

This is a question originally posted by @NightMICU     
asked by manix 02.12.2015 в 07:39
source

2 answers

5

You can operate the redirect effectively with a Middleware class. Let me give you an idea:

namespace MyApp\Http\Middleware;

use Closure;

class ProtocoloHttps {

    public function handle($request, Closure $next)
    {
        if (!$request->secure() && env('APP_ENV') === 'prod') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request); 
    }
}

To apply this class in each request you must add the class to the Kernel.php file as seen below:

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',

    // Redirección de protocolo
    'MyApp\Http\Middleware\ProtocolHttps'       

];

When you add the class to the $middleware array, all requests for your application will be redirected to HTTPS if:

  • The current request comes from the normal http protocol.
  • If the environment of your application is equal to prod (adjust this value to your preferences).
  • The answer was given by me from the original statement.     
    answered by 02.12.2015 в 07:39
    0

    Look at the easiest way for you to do the validation from your action in the controller, if the condition is not met, you put:

    return redirect('aqui la ruta a donde lo quieres llevar');
    

    For me, this is the simplest solution.

        
    answered by 22.12.2015 в 13:03