Laravel Redirect to Secure Connection from Http to Https

In Laravel's .env file we can set APP_URL . Either the url starts with http or https, user can access our web application on both protocol. As Http is not considered as secure connection type, you may wonder how can we transfer or redirect our user to secure connection that is Https protocol by default.

So in this Laravel short tutorial I will explain how we can transfer or redirect all the user from http protocol to https in easy way. that is from un-secure connection to secure connection.

For that lets open the .htaccess file that is in our /public directory and add the following lines of code with the RewriteEngine On

RewriteEngine On
    RewriteCond     %{SERVER_PORT} ^80$
    RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R] 

All together the whole file will look like:

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

    RewriteEngine On
    RewriteCond     %{SERVER_PORT} ^80$
    RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

    # 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> 

The above sample file is taken from Laravel 8.x.

Hope you get something useful from this article. Thanks for reading.

Comments :