Setting up HTTPS redirects on Heroku Laravel Instance

An illustration or image

Introduction

I am going to keep this post really short.

Last week I worked on cleaning up parts of my personal site and one thing I really wanted to solve was to force all requests to be served via HTTPS.

I tried a couple of options, like forcing the redirect using .HTACCESS this led to multiple redirects.

After a few more tries, I finally decided to solve this in code.

I ended up just implementing this as a middleware.

Solution

Create Middleware

  • $ php artisan make:middleware HttpsProtocol

Find and fill out HttpsProtocol.php

01: ...
02: 
03: namespace App\Http\Middleware;
04: 
05: use Closure;
06: 
07: class HttpsProtocol
08: {
09:     /**
10:      * Handle an incoming request.
11:      *
12:      * @param    \Illuminate\Http\Request  $request
13:      * @param    \Closure  $next
14:      * @return  mixed
15:      */
16:     public function handle($request, Closure $next)
17:     {
18:         if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'http'
19:          && \App::environment() === 'production') {
20:             return redirect()->secure($request->getRequestUri());
21:         }
22: 
23: ...

Register middleware in app\HTTP\Kernel.php

Look for protected $middleware = [ ... and add the line \App\Http\Middleware\HttpsProtocol::class, to the end of the array.

The end result should look something like below.

01:  protected $middleware = [
02:         \App\Http\Middleware\CheckForMaintenanceMode::class,
03:         \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
04:         \App\Http\Middleware\TrimStrings::class,
05:         \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
06:         \App\Http\Middleware\TrustProxies::class,
07:         \App\Http\Middleware\HttpsProtocol::class,
08:     ];

And that worked for me ...

Here is another article for you 😊 "BrainFuck Interpreter using method chaining"