Redirect HTTP To HTTPS Using Laravel Middleware

Today, We want to share with you Redirect HTTP To HTTPS Using Laravel Middleware.In this post we will show you laravel redirect http to https htaccess, hear for laravel redirects to http instead of https we will give you demo and example for implement.In this post, we will learn about Laravel 6 Middleware 301 Redirect, from http to https or non-www to www site redirect with an example.

Redirect HTTP To HTTPS Using Laravel Middleware

There are the Following The simple About laravel redirect to url with parameters Full Information With Example and source code.

Read Also:  Laravel 6 Redirect Function

As I will cover this Post with live Working example to develop laravel redirect with request data, so the laravel redirect with variable is used for this example is following below.

redirect the user HTTP to HTTPS using Laravel code

create a simple middleware using CMD to run commands

php artisan make:middleware RedirectHttpEx

app\Http\Middleware\RedirectHttpEx.php
public function handle($request, Closure $next){
  if (!$request->secure()) {
      return redirect()->secure($request->path());
  }
  return $next($request);
}

app/Http/Kernel.php

protected $middleware = [
   ....
   \App\Http\Middleware\RedirectHttpEx::class,
   ....
];

Example 2: Laravel 6 redirect to HTTPS

AppServiceProvider > boot method

\URL::forceScheme('https');

laravel 6 redirect http to https

Laravel Middleware -> handle method

Read Also:  Laravel redirect route with query string example

public function handle($request, Closure $next)
    {
        if(config('app.env') == 'production'){

            $host = $request->header('host');
            if (substr($host, 0, 4) != 'www.') {
                if(!$request->secure()){
                    $request->server->set('HTTPS', true);
                }
                $request->headers->set('host', 'www.'.$host);
                return Redirect::to($request->path(),301);
            }else{
                if(!$request->secure()){
                    $request->server->set('HTTPS', true);
                    return Redirect::to($request->path(),301);
                }
            }
        }

        return $next($request);
    }

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel 5.8, 6.0, 6.2 force https.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.