I know we can achieve same with other methods but I am going with Laravel Middleware. So let’s create Middleware called “ForceHttpProtocol”.
Our ForceHttpProtocol middleware will redirect every request to https if – The current request comes with no secure protocol means http and If your environment is equals to prod. So, just adjust the settings according to your preferences.
Using your Terminal, navigate to your project’s root directory and issue the following artisan command:
代碼: 選擇全部
php artisan make:middleware ForceHttpProtocol
代碼: 選擇全部
<?php
namespace App\Http\Middleware;
use Closure;
class ForceHttpProtocol {
public function handle($request, Closure $next) {
if (!$request->secure() && env('APP_ENV') === 'pro') {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
代碼: 選擇全部
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\ForceHttpProtocol'
];
代碼: 選擇全部
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\ForceHttpProtocol::class,
];
代碼: 選擇全部
Route::get('projects', ['middleware' => 'forceSsl', function()
{
echo 'Hello, I am secure';
}]);
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.