在 Laravel 5.3 中仅使用 https 协议创建两条路由

Make only two routes with https protocol in Laravel 5.3

我只想要 https 中的付款结帐页面。我在 http:// 中有一个网站,我使用 Stripe 信用卡实现付款结帐,但 Stripe 仅适用于 https...

我希望我的所有网站都有 http,除了 /payment-date 页面和 payment-data-post 页面,以便使用安全协议将数据发送到 Stripe。

我怎么能在 https 上只有那两个页面?

路线是:

Route::get('/payment-data',['as'=> 'payment_data','uses' => 'WebController@getPaymentData']);

Route::post('/post-payment-data', ['as'  => 'post_payment_data', 'uses' => 'WebController@postPaymentData']);

我只想要 https

中的这条路由

框架是Laravel 5.3

您可以在声明路由时通过传递 ['http' => true] 或 ['https' => true] 作为选项来指定路由是 HTTP 还是 HTTPS,如果您不这样做的话指定这些选项然后它应该只使用与您当前访问页面相同的协议。

Route::post('/form', ['uses' => 'FormController@postForm', 'https' => true]);

我认为一个好的做法是创建一个中间件,然后您可以在任何您喜欢的路由上使用它。

使用终端,导航到项目的根目录并发出以下 artisan 命令 (创建 ForceHttpProtocol 中间件):

php artisan make:middleware ForceHttpProtocol

更改新创建的 /app/Http/Middleware/ForceHttpProtocol.php 使其看起来像这样(仅适用于生产):

<?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);
    }

}

下一步是通过添加 'App\Http\Middleware\ForceHttpProtocol' 来更新 /app/Http/Kernel.php将使 Laravel 知道您的自定义中间件。


如果你只想在特定的路由上应用中间件,你只需要通过在 $routeMiddleware 数组中添加 'App\Http\Middleware\ForceHttpProtocol' 指令来将中间件分配给路由。

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    ...
    'forceSSL' => App\Http\Middleware\ForceHttpProtocol::class,

];

只需像往常一样使用新创建的中间件即可:

Route::get('payment-date', ['middleware' => 'forceSSL', function()
{
   // do stuff
}]);

应该就是了!