Search

How To Force Redirect HTTP To HTTPS In Laravel?

  • Share this:
post-title

Welcome guys, In this article, we will see how to force redirect HTTP to HTTPS in laravel Here we will show you two methods in laravel redirect to HTTPS first is laravel redirect HTTP to HTTPS via htaccess and the second is laravel force redirect HTTPS using middleware.

What is HTTP & What is HTTPS?

HTTP : HTTP stands for Hypertext Transfer Protocol, and it is a protocol – or a prescribed order and syntax for presenting information – used for transferring data over a network. Most information that is sent over the Internet, including website content and API calls, uses the HTTP protocol. There are two main kinds of HTTP messages: requests and responses.

HTTPS : The S in HTTPS stands for "secure." HTTPS uses TLS (or SSL) to encrypt HTTP requests and responses, so in the example above, instead of the text, an attacker would see a bunch of seemingly random characters.

Step: 1 HTTP To HTTPS Using .htaccess  

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
  
    RewriteEngine On
  
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  
    # 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>

laravel default provide htaccess and i have addedd some extra code.

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Step: 2 HTTP To HTTPS Using middleware

Using artisan create the middleware template:

php artisan make:middleware HttpsMiddleware

This creates the file app/Http/Middleware/HttpsMiddleware.php.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class HttpsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (!$request->secure()) {
            return redirect()->secure($request->path());
        }
        return $next($request);
    }
}
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (53)