[Laravel] LAMP+Laravel 學習筆記-ForceSSL

強迫Laravel網站使用SSL
Laravel 5.4
1.新增middleware :app\Http\Middleware\ForceSSL.php
2.修改Kernel: app\Http\kernel.php $routeMiddleware
   設定 使用forceSSL
3.修改route : routes\web.php
 

1.middleware
新增app\Http\Middleware\ForceSSL.php
 

<?php

namespace App\Http\Middleware;

use Closure;

class ForceSSL
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->secure()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

2.修改kernel : app\Htt\Kernel.php
 

  /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'forceSSL' => \App\Http\Middleware\ForceSSL::class,
    ];


3.設定路由使用SSL middleware
 

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::group(['middleware'=>'forceSSL'], function() {
    Route::get('/', 'IndexController@index')->name('index');
    Route::get('/search', 'SearchController@index')->name('search');
});