How to force HTTPS on all routes in laravel? 2 Easy Methods

March 5, 2023
Laravel
How to force HTTPS on all routes in laravel? 2 Easy Methods

In this guide, you will learn how to force HTTPS on all routes in laravel. We will be forcing HTTP to serve all routes to HTTPS.

We will be sharing 2 ways forcing HTTPS on all routes in laravel.

This tutorial is valid for all types of laravel versions including laravel 6, laravel 7, laravel 8 and laravel 9.

Lets get started.

Method 1: Using .htaccess force HTTPS on all routes in laravel

In this method, we will using .htacess in order to force HTTPS on the routes in laravel. In your public/.htaccess file.

At the end of the file add the following code:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This will automatically converts the all the URLs of laravel application to be served with https.

Here is the final .htaccess file will look like:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

# Disable Directory listing
Options -Indexes

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Method 2: Using ServiceProvider force HTTPS on all routes in laravel

In this method, we will using add some code in the service provider file in order to force HTTPS on all routes in laravel. Go the app/Providers/AppServiceProvider.php file.

Add the following code in the boot function:

 public function boot()
    {
        \URL::forceScheme('https');

    }

This will allow your to convert and force all URLs in the laravel application to be served with HTTPS.

Conclusion

In the above article, we have shared 2 ways of forcing HTTPS on all routes in laravel application.

Let me know if you have any questions, see you at the next one 🙂

Write a Reply or Comment

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


Icon