Sometimes people don't link to the secure (https) version of your site, this can be an old link or the user who placed the link is just lazy to add the extra character.

To force redirect a http url to https I use in some cases a middleware to handle the redirect. This is just a simple solution and don't require a change to the server or nginx configuration.

You can make the middleware by running php artisan make:middleware HttpsProtocolMiddleware and it will generate a file like below (or just copy and paste this file in app/Http/Middleware/HttpsProtocolMiddleware.php). This will check if the request is secure, if it is not secure, it will redirect the user to the secure/https URL.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

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

        return $next($request);
    }
}

In your HTTP Kernel (app/Http/Kernel.php) you can place the created middleware in the web group, which is applied to every request to your Laravel application.

protected $middlewareGroups = [
    'web' => [
       \App\Http\Middleware\EncryptCookies::class,
       \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
       \Illuminate\Session\Middleware\StartSession::class,
       //\Illuminate\Session\Middleware\AuthenticateSession::class,
       \Illuminate\View\Middleware\ShareErrorsFromSession::class,
       \App\Http\Middleware\VerifyCsrfToken::class,
       \Illuminate\Routing\Middleware\SubstituteBindings::class,
       \App\Http\Middleware\HttpsProtocolMiddleware::class
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

But why don't you just use \Illuminate\Support\Facades\URL::forceScheme('https'); ? It's a simple answer, this method don't redirect the user to the secure version of your site, so the user still access the unsecure/http version, it just force Laravel to generate secure/https links.

Robin Dirksen

Robin Dirksen

On my blog you can find articles that I've found useful. This is just a simple blog built with Wink.