Categories
Laravel

How to redirect requests to HTTPS in Laravel 5

I know we can achieve same with other methods but I am going do it with the Laravel’s Middleware. So let’s create Middleware called ForceHttpProtocol.

How it will work

Our ForceHttpProtocol middleware will redirect every request to https if – The current request comes with no security protocol means HTTP and If your environment is equaled to prod. So, just adjust the settings according to your preferences.

Create middleware

Using your Terminal, navigate to your project’s root directory and issue the following artisan command:

Now, using your editor of choice, change the newly created /app/Http/Middleware/ForceHttpProtocol.php so it look like this:

Next update /app/Http/Kernel.php adding the 'App\Http\Middleware\ForceHttpProtocol' instruction which will make Laravel aware of your custom middleware:

If you want to apply middleware only on specific routes you just have to assign middleware to routes by adding 'App\Http\Middleware\ForceHttpProtocol' instruction to $routeMiddleware array.

If route middleware – just use your middleware as you’re used to:

That is it.

By Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

2 replies on “How to redirect requests to HTTPS in Laravel 5”

Leave a Reply

Your email address will not be published. Required fields are marked *