EDDYMENS

Setting up HTTPS redirects on Heroku Laravel Instance

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

<?php

namespace App\Http\Middleware;

use Closure;

class HttpsProtocol
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'http'
         && \App::environment() === 'production') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

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.

 protected $middleware = [
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\HttpsProtocol::class,
    ];

And that worked for me ...