Way*_*her 3 https routes http laravel
我的服务器使用 SSL,因此我的所有路由/url 都使用 https。我最近在 Laravel 5.7 中发现了一个错误,该错误在尝试使用电子邮件验证时暴露出来,该错误在带有 https 的服务器上不起作用。我不会详细讨论该问题,因为我还有另一个问题。我想保持这个简单。我的 .env 文件中有以下设置:
APP_USE_HTTPS=true
APP_URL=https://www.example.com
APP_ENV=production
Run Code Online (Sandbox Code Playgroud)
我在 AppServiceProvider 的 boot() 方法中有以下内容
if (env('APP_USE_HTTPS')) {
Log::info('AppServiceProvider: forcing URLs to use https');
URL::forceScheme('https');
}
Run Code Online (Sandbox Code Playgroud)
这可能有点矫枉过正,但为了尝试解决这个问题,我还将以下代码放在我的 web.php 路由文件的顶部”
if (env('APP_USE_HTTPS')) {
Log::info('Routes: forcing URLs to use https');
URL::forceScheme('https');
}
Route::get('/', 'PublicController@getHome');
Route::get('home', 'PublicController@getHome');
Run Code Online (Sandbox Code Playgroud)
然后在我的 PublicController.getHome() 方法中我输入了以下代码:
public function getHome()
{
$currentPath= Request::fullUrl();
Log::info($currentPath);
return view('public.home');
}
Run Code Online (Sandbox Code Playgroud)
现在我转到浏览器并在地址栏中输入:
https://www.example.com
Run Code Online (Sandbox Code Playgroud)
我在日志文件中得到了这个:
AppServiceProvider: forcing URLs to use https
Routes: forcing URLs to use https
http://www.example.com
Run Code Online (Sandbox Code Playgroud)
正如您从最后一条日志消息中看到的那样,laravel 始终使用 http 而不是 https 的事实开始产生问题。从签署的路线开始。我正在尝试使用内置电子邮件验证,但签名是使用 https 路由生成的,并且发送给用户的电子邮件的 URL 中确实有 https,用于返回同一服务器。然而,路由验证使用的是 http(即使使用了 https),因此它会生成不同的签名,因此所有验证链接都会失败并出现 403 错误。
我有什么遗漏的吗?我似乎找不到代码来显示 Laravel 如何知道使用 https 或 http,还是只是为 http 进行了硬编码?
感谢你给与我的帮助。
*** 更新以显示 Shaielndra Gupta 答案的问题 ****
实现中间件后,下面是我使用的代码,但正如您将看到的,核心问题存在于处理 url 的所有方法中。例如:
$request->secure()
Run Code Online (Sandbox Code Playgroud)
即使使用 https,也会返回 false。然后通过调用:
redirect()->secure($request->getRequestUri());
Run Code Online (Sandbox Code Playgroud)
没有什么好处,因为这会导致路由再次循环回此方法,这仍然为 secure() 返回 false,基本上创建了一个无限循环(或无限太多的重定向)
class ForceHttpsProtocol {
public function handle($request, Closure $next) {
Log::info('request uri: '.$request->fullUrl());
Log::info('secure: '.($request->secure() ? 'yes' : 'no'));
if (!$request->secure() && env('APP_USE_HTTPS')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Run Code Online (Sandbox Code Playgroud)
当您尝试访问任何页面 1 次时,即使使用https://www.example.com,上述代码的日志也会生成以下内容
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
request uri: http://www.example.com
secure: no
Run Code Online (Sandbox Code Playgroud)
<一遍又一遍直到页面超时>
经过大量研究,我终于发现了问题所在。我的实时服务器安装在负载均衡器后面的Amazon EC2 服务器上。负载均衡器正在接收 (https) 请求并处理所有 SSL 要求,然后将请求作为 http 转发到我的网站。为了解决这个问题,我必须安装 fideloper/TrustedProxy 包。这个包允许我的网站信任代理并获取请求的有效标头,因此它现在知道请求实际上是使用 https 发送的。
Laravel 写了一篇文章准确地描述了我的情况。 https://laravel-news.com/trusted-proxy
这是我安装的软件包: https: //github.com/fideloper/TrustedProxy
| 归档时间: |
|
| 查看次数: |
5048 次 |
| 最近记录: |