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.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...