EDDYMENS

Last updated 2019-12-17 21:20:01

Setting Up HTTPS Redirects On Heroku Laravel Instance

Table of contents

 [→]

Introduction

I am going to keep this post really short.

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 with code.

I ended up just implementing this as a middleware.

Creating a 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 the 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 thats what worked for me ...

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"