Ad

Applying Ssl Only To Admin Routes Of Site

- 1 answer

I have a website made in PHP Laravel 5.1 with the PingPong admin package for the administration CMS of this very site.

The routes are like:

mywebsite » for the public website

mywebsite/admin » for the admin CMS

My client wants to add a SSL protocol only in the mywebsite/admin route. Is it possible to do that? If it is, do I need to add some extra lines of code for that?

Ad

Answer

You could create a middleware that redirects when the URL is not secure (via HTTPS). And then enable that middleware on the routes that you want to enforce SSL:

<?php // app/Http/Middleware/Secure.php

namespace App\Http\Middleware;

use Closure;

class Secure
{
    public function handle($request, Closure $next)
    {
        if (!$request->isSecure()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

Add the middleware in your app/Http/Kernel.php:

protected $routeMiddleware = [
    'secure' => \App\Http\Middleware\Secure::class
];

And enable the middleware on the admin routes, for example using a route group:

Route::group(['middleware' => 'secure', 'prefix' => 'admin'], function () {
    // here your routes (without 'admin/' prefix)
});

Now when, someone goes to the admin URL via normal HTTP, he will be redirected to the HTTPS version of that route.

Of course, you need to setup a certificate in a proper way such that the site can be accessed by both HTTP and HTTPS.

Ad
source: stackoverflow.com
Ad