Secured URLs has a key role to secure your web application in many ways. In my opinion, you should always serve the content via a secure URL and this is one of many ways to prevent from exploits. Oftentimes, applications will have a secure URL and URL without HTTPS.
So our application needs to decide whether it will serve the content via a secured URL or non secured URL. In today’s tutorial, we are working on Laravel, a well-known PHP framework, and we learn how to force Laravel to use HTTPS URL with the help of middleware. This way Laravel forces https routes throughout the application.
In this example, we create a middleware called ForceHttpsMiddleWare.php, and by running the below command you can generate a middleware.
php artisan make:middleware ForceHttpsMiddleWare
This function will check if the request is secure, and if it’s not secure it will redirect the user to a secured URL.
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\App; class ForceHttpsMiddleWare { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->secure() && app()->environment('production')) { return redirect()->secure($request->getRequestUri()); } 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.
protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \App\Http\Middleware\ForceHttpsMiddleWare::class ], ];
You can just disable this https redirection by removing this code from your source code.
A small caveat for this approach, it does not handles the https for non Laravel urls such as images, js, css etc.
That’s it, you are ready to use your newly created middleware.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply