Monday, 3 October 2016

How to redirect http to https in laravel using middleware

In this post i will show you how to redirect all your http request to https you can do it with the help of middleware.The middleware will redirect every request to https if your environment is production or you can adjust the setting according to your need.

Laravel Middleware

Step 1: Using Command line you can create a middleware.

php artisan make:middleware HttpProtocol

Edit this file in your favourite editor and its look like this.


namespace App\Http\Middleware;

use Closure;

class HttpProtocol

    public function handle($request, Closure $next)

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

        return $next($request);

Step 2: Update the /app/Http/Kernel.php by adding 'App\Http\Middleware\HttpProtocol' into middleware array property.

protected $middleware = [

If you want to apply middleware only on specific routes the you need to assign middleware route by adding 'App\Http\Middleware\HttpProtocol' in $routeMiddleware array.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'forceSsl' => App\Http\Middleware\HttpProtocol::class,

Step 3: Now you can use the middleware like.

Route::get('projects', ['middleware' => 'forceSsl', function()
   echo 'welcome for https';

Hope you like the post for any help or suggestion please comment below.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts