Cloudflare offers a great flexible SSL service allowing anyone to secure their site for free. Unfortunately, you can run into some issues straight out of the box as we ourselves found out when implementing Cloudflare’s SSL on this very site. For more established content management systems, Cloudflare does supply plugins that fix these problems without the need of additional code. However, in this case we will be guiding you through the process of setting up SSL with Coaster CMS – and yes, that does include writing some code.
Prerequisites
Of course, a Cloudflare account of any plan, free or paid, will be required for this tutorial. This tutorial will also assume you have some experience with object oriented PHP, and preferably some familiarity with the Laravel framework.
- A Cloudflare account
- Some PHP knowledge
Creating the middleware
To deal with HTTPS requests we will be creating a middleware. To create a new middleware type the command below into a terminal window.
1 |
php artisan make:middleware HttpsProtocol |
This command will create a new file called HttpsProtocol.php within app/Http/Middleware. Open up this file with your favourite text editor, e.g. Notepad and at the top of the file underneath namespace type ‘use Closure;’. Finally, within the class parentheses create a handle method:
1 2 3 4 5 6 7 8 |
public function handle($request, Closure $next) { $request->setTrustedProxies( [ $request->getClientIp() ] ); if (!$request->secure()) { return redirect()->secure($request->getRequestUri()); } return $next($request); } |
All in all your HttpsProtocol.php file should look as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace App\Http\Middleware; use Closure; class HttpsProtocol { public function handle($request, Closure $next) { $request->setTrustedProxies( [ $request->getClientIp() ] ); if (!$request->secure()) { return redirect()->secure($request->getRequestUri()); } return $next($request); } } |
Save this file and navigate to your Kernel.php file located within the root of your site’s app/Http directory. Find the $middleware variable and add the following code:
1 |
\App\Http\Middleware\HttpsProtocol::class, |
This class sets the current client’s IP as being a trusted proxy, and therefore this solution would not only work for Cloudflare but also for other similar services. If you wanted to you could instead replace this with an array of Cloudflare’s IPs.
Summary
That’s it, your site should now work with Cloudflare’s Flexible SSL. If not, leave us a comment below or tweet us on Twitter.