Laravel 5 - 重定向到 HTTPS [英] Laravel 5 - redirect to HTTPS

查看:38
本文介绍了Laravel 5 - 重定向到 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在处理我的第一个 Laravel 5 项目,但不确定在哪里或如何放置逻辑以在我的应用程序上强制使用 HTTPS.这里的关键是有许多域指向应用程序,并且只有三分之二使用 SSL(第三个是后备域,长话短说).所以我想在我的应用程序的逻辑中而不是 .htaccess 中处理这个问题.

在 Laravel 4.2 中,我使用位于 filters.php 中的代码完成了重定向:

App::before(function($request){如果(!请求::安全()){返回重定向::安全(请求::路径());}});

我认为应该在中间件中实现类似的东西,但我无法完全弄清楚使用它.

谢谢!

更新

如果您像我一样使用 Cloudflare,这是通过在您的控制面板中添加新的页面规则来实现的.

解决方案

您可以使其与中间件类一起使用.让我给你一个主意.

命名空间 MyAppHttpMiddleware;使用闭包;使用 IlluminateSupportFacadesApp;类 HttpsProtocol {公共函数句柄($request, Closure $next){if (!$request->secure() && App::environment() === '生产') {return redirect()->secure($request->getRequestUri());}返回 $next($request);}}

然后,将此中间件应用于每个请求,在 Kernel.php 文件中添加设置规则,如下所示:

受保护的 $middleware = ['IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode','IlluminateCookieMiddlewareEncryptCookies','IlluminateCookieMiddlewareAddQueuedCookiesToResponse','照明会话中间件启动会话','IlluminateViewMiddlewareShareErrorsFromSession',//附加自定义中间件'MyAppHttpMiddlewareHttpsProtocol'];

在上面的示例中,如果出现以下情况,中间件会将每个请求重定向到 https:

  1. 当前请求没有安全协议 (http)
  2. 如果您的环境等于 production.因此,只需根据您的喜好调整设置即可.

Cloudflare

我在带有 WildCard SSL 的生产环境中使用此代码,并且该代码运行正常.如果我删除 &&App::environment() === 'production' 并在本地主机中测试它,重定向也有效.因此,是否安装 SSL 都不是问题.看起来您需要非常注意您的 Cloudflare 层才能重定向到 Https 协议.

编辑 23/03/2015

感谢 @Adam Link 的建议:这很可能是由 Cloudflare 传递的标头引起的.CloudFlare 可能通过 HTTP 访问您的服务器并传递 X-Forwarded-Proto 标头,声明它正在转发 HTTPS 请求.您需要在中间件中添加另一行说...

$request->setTrustedProxies( [ $request->getClientIp() ] );

...信任 CloudFlare 发送的标头.这将停止重定向循环

编辑 27/09/2016 - Laravel v5.3

只需要将中间件类添加到kernel.php文件中的web组:

protected $middlewareGroups = ['网络' =>[IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,IlluminateSessionMiddlewareStartSession::class,IlluminateViewMiddlewareShareErrorsFromSession::class,//这里MyAppHttpMiddlewareHttpsProtocol::class],];

<块引用>

请记住,web 组默认应用于每个路由,因此您无需在路由和控制器中显式设置 web.

编辑 23/08/2018 - Laravel v5.7

  • 要根据环境重定向请求,您可以使用 App::environment() === 'production'.对于以前的版本是env('APP_ENV') === '生产'.
  • 使用 URL::forceScheme('https'); 实际上不会重定向.网站呈现后,它只是使用 https:// 构建链接.

Working on my first Laravel 5 project and not sure where or how to place logic to force HTTPS on my app. The clincher here is that there are many domains pointing to the app and only two out of three use SSL (the third is a fallback domain, long story). So I'd like to handle this in my app's logic rather than .htaccess.

In Laravel 4.2 I accomplished the redirect with this code, located in filters.php:

App::before(function($request)
{
    if( ! Request::secure())
    {
        return Redirect::secure(Request::path());
    }
});

I'm thinking Middleware is where something like this should be implemented but I cannot quite figure this out using it.

Thanks!

UPDATE

If you are using Cloudflare like I am, this is accomplished by adding a new Page Rule in your control panel.

解决方案

You can make it works with a Middleware class. Let me give you an idea.

namespace MyAppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesApp;

class HttpsProtocol {

    public function handle($request, Closure $next)
    {
            if (!$request->secure() && App::environment() === 'production') {
                return redirect()->secure($request->getRequestUri());
            }

            return $next($request); 
    }
}

Then, apply this middleware to every request adding setting the rule at Kernel.php file, like so:

protected $middleware = [
    'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode',
    'IlluminateCookieMiddlewareEncryptCookies',
    'IlluminateCookieMiddlewareAddQueuedCookiesToResponse',
    'IlluminateSessionMiddlewareStartSession',
    'IlluminateViewMiddlewareShareErrorsFromSession',

    // appending custom middleware 
    'MyAppHttpMiddlewareHttpsProtocol'       

];

At sample above, the middleware will redirect every request to https if:

  1. The current request comes with no secure protocol (http)
  2. If your environment is equals to production. So, just adjust the settings according to your preferences.

Cloudflare

I am using this code in production environment with a WildCard SSL and the code works correctly. If I remove && App::environment() === 'production' and test it in localhost, the redirection also works. So, having or not a installed SSL is not the problem. Looks like you need to keep a very hard attention to your Cloudflare layer in order to get redirected to Https protocol.

Edit 23/03/2015

Thanks to @Adam Link's suggestion: it is likely caused by the headers that Cloudflare is passing. CloudFlare likely hits your server via HTTP and passes a X-Forwarded-Proto header that declares it is forwarding a HTTPS request. You need add another line in your Middleware that say...

$request->setTrustedProxies( [ $request->getClientIp() ] ); 

...to trust the headers CloudFlare is sending. This will stop the redirect loop

Edit 27/09/2016 - Laravel v5.3

Just need to add the middleware class into web group in kernel.php file:

protected $middlewareGroups = [
    'web' => [
        IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
        IlluminateSessionMiddlewareStartSession::class,
        IlluminateViewMiddlewareShareErrorsFromSession::class,

        // here
        MyAppHttpMiddlewareHttpsProtocol::class

    ],
];

Remember that web group is applied to every route by default, so you do not need to set web explicitly in routes nor controllers.

Edit 23/08/2018 - Laravel v5.7

  • To redirect a request depending the environment you can use App::environment() === 'production'. For previous version was env('APP_ENV') === 'production'.
  • Using URL::forceScheme('https'); actually does not redirect. It just builds links with https:// once the website is rendered.

这篇关于Laravel 5 - 重定向到 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆