0

I want to redirect the HTTP traffic to HTTPS without using .htaccess file in laravel 5.2? How can i do that, Any solution will be appreciated.

Mehroz Munir
  • 2,248
  • 1
  • 18
  • 16

1 Answers1

1
if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

For Laravel 5.2 you can do this:

create new middleware (you can do it by command php artisan make:middleware nameMiddleware, eg. php artisan make:middleware forceSSL

In this middleware (/app/Http/Middleware/nameMiddleware.php) put this:

<?php

namespace App\Http\Middleware;

use Closure;

class nameMiddleware {

    public function handle($request, Closure $next) {

        if (!$request->secure() && env('APP_ENV') === 'prod') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }

}

Register your middleware in /app/http/Kernel.php

$middlewares = [
...
'\app\Http\Middleware\nameMiddleware'
];

Add the middleware to $routeMiddleware array.

After this, you can add the middleware directly into Route::get('/', ['middleware' => 'nameMiddleware'] ...);

mabezdek
  • 87
  • 1
  • 13