Force http to https redirect in Laravel

8934
Force http to https redirect in Laravel 5

HTTPS is a secure version of HTTP. HTTPS helps keep your browsing safe by securely connecting your browser or app with the websites you visit. There are various vendors that provide SSL such as Comodo, DigiCert, GlobalSign, RapidSSL and so on that provide paid SSL. There is also a free one called Let’s Encrypt.

If the website doesn’t use SSL, then google chrome( > version 70) will show insecure on the address bar as below.

insecure web in google chrome
Image Source: Google

There are various methods to redirect http request to https in laravel. Below are the steps that redirect http request to https.

1Using Middleware

The first approach we are going to implement is through middleware. I assume you are familiar with middleware in laravel. So, let’s start by creating middleware through artisan command:

php artisan make:middleware HttpsMiddleware

After it, open the newly created middleware and add some code to check if the environment is production or not. If the environment is production, then we will redirect the URL to https.

Finally, add the middleware in the kernel.php.

2Using AppServiceProvider

We can force the website to serve through https using laravel default AppServiceProvider. Navigate to the directory /app/providers/ and open AppServiceProvider. Edit the boot method which finally looks like below:

3Using .htaccess

The third method we may use is using .htacess file. By default, laravel comes with valid .htaccess file. We can make some changes so that the web application is served through https. Below is my final working .htaccess that redirect my applcation through https.

4Conclusion

Using SSL is a must these days. SSL not only secure your web transaction but also helps in SEO and higher rank on google. This is all about enforcing HTTP to https. If you have any feedback or comment, don’t forget to drop below in the comment section.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.