1 頁 (共 1 頁)

Laravel 5 redirect (some) requests to HTTPS

發表於 : 2016-07-17 20:19:06
yehlu
https://arjunphp.com/laravel-5-redirect ... -to-https/

I know we can achieve same with other methods but I am going with Laravel Middleware. So let’s create Middleware called “ForceHttpProtocol”.

Our ForceHttpProtocol middleware will redirect every request to https if – The current request comes with no secure protocol means http and If your environment is equals to prod. So, just adjust the settings according to your preferences.

Using your Terminal, navigate to your project’s root directory and issue the following artisan command:

代碼: 選擇全部

 php artisan make:middleware ForceHttpProtocol
Now, using your editor of choice, change the newly created /app/Http/Middleware/ForceHttpProtocol.php so it look like this:

代碼: 選擇全部

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class ForceHttpProtocol {
 
    public function handle($request, Closure $next) {
 
        if (!$request->secure() && env('APP_ENV') === 'pro') {
            return redirect()->secure($request->getRequestUri());
        }
 
        return $next($request);
    }
 
}
Next update /app/Http/Kernel.php adding the 'App\Http\Middleware\ForceHttpProtocol' instruction which will make Laravel aware of your custom middleware:

代碼: 選擇全部

    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\ForceHttpProtocol'
 
    ];
If you want to apply middleware only on specific routes you just have to assign middleware to routes by adding 'App\Http\Middleware\ForceHttpProtocol' instruction to $routeMiddleware array.

代碼: 選擇全部

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'forceSsl' => App\Http\Middleware\ForceHttpProtocol::class,
 
];
If route middleware – just use your middleware as you’re used to:

代碼: 選擇全部

Route::get('projects', ['middleware' => 'forceSsl', function()
{
   echo 'Hello, I am secure';
}]);
That is it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.