After installing an SSL certificate, the next step is redirecting your traffic from HTTP to HTTPS. That’s a lot easier in simple PHP websites but for Laravel websites, we are going to follow the code snippets below.
Make Middleware for Redirect
Create file in \app\Http\Middleware\HttpsProtocol.php
. Open file HttpsProtocol.php
and write the following code.
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\App;
use Closure;
class HttpsProtocol {
public function handle($request, Closure $next) {
if ( App::environment(['staging', 'production']) && !$request->secure() ) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Connect in Kernel.php
Open file \app\Http\Kernel.php
and add line \App\Http\Middleware\HttpsProtocol::class,
in the middlewareGroups array.
<?php
// some existing code
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\HttpsProtocol::class, // add line here at the end
],
];
Define Environment
Open .env
file and specify the environment, we are only redirection on staging and production environment.
APP_ENV=production
Now your Laravel application is served on https for production
and staging
environments.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
The point of view of your article has taught me a lot, and I already know how to improve the paper on gate.oi, thank you.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?