You can switch your HTTP website to an HTTPS connection in a few different ways. I have outlined how to use a middleware in this article.
In some cases, I use middleware to manage redirection in order to force an http link to become an https link. There is no need to alter the server's or nginx's configuration because this is merely a straightforward fix.
Force HTTPS with Middleware
Run "php artisan make:middleware HttpsProtocolMiddleware" to create the middleware,
which will result in the file shown below (you can also copy and paste this file into app/Http/Middleware/HttpsProtocolMiddleware.php).
This will determine whether the request is secure and redirect the user to a secure/https URL if it is not.
In the terminal, hit the below command.
php artisan make:middleware HttpsProtocolMiddleware
It will create a file inside the app/Http/Middleware folder.
After creating the middleware, let’s add the condition to check the incoming requests.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class HttpsProtocolMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (!$request->secure() && env('APP_ENV') === "production") {
return redirect()->secure($request->path());
}
return $next($request);
}
}
In your HTTP Kernel (app/Http/Kernel.php) you can place the created middleware in the web group, which is applied to every request to your Laravel application.
Registered your middleware into this way
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\HttpsProtocolMiddleware::class,
];
env('APP_ENV') === "production" this section added to your local project. Update your live server .env file and APP_ENV=production.
Force HTTPS with .htaccess
You can change all of your HTTP queries to HTTPS using a.htaccess file. Just a few lines of code will check to see if the request is HTTPS, and if it isn't, your application will redirect the user to the HTTPS version.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Hope, this article will help you to How to force HTTPS in a Laravel project.