且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

反向代理背后的 Laravel 路由

更新时间:2022-06-20 18:35:26

当 Laravel 5 应用程序不知道位于 SSL 负载平衡器之后时,我遇到了相同(或类似的问题).

I ran into the same (or similar problem), when a Laravel 5 application was not aware of being behind an SSL load-balancer.

我有以下设计:

  • 客户端通过 HTTPS 与 SSL 负载平衡器通信
  • SSL 负载平衡器通过 HTTP 与后端服务器通信

然而,这会导致 HTML 代码中的所有 URL 都使用 http://架构生成.

That, however, causes all the URLs in the HTML code to be generated with http:// schema.

以下是实现此工作的快速解决方法,包括架构(http 与 https):

The following is a quick'n'dirty workaround to make this work, including the schema (http vs. https):

将以下代码放在app/Http/routes.php

在最新版本的 Laravel 中,使用 web/routes.php

In latest version of laravel, use web/routes.php

$proxy_url    = getenv('PROXY_URL');
$proxy_schema = getenv('PROXY_SCHEMA');

if (!empty($proxy_url)) {
   URL::forceRootUrl($proxy_url);
}

if (!empty($proxy_schema)) {
   URL::forceSchema($proxy_schema);
}

然后将以下行添加到 .env 文件中:

then add the following line into .env file:

PROXY_URL = http://igateway.somedomain.com

如果您还需要将生成的 HTML 代码中的架构从 http:// 更改为 https://,只需添加以下行:>

If you also need to change schema in the generated HTML code from http:// to https://, just add the following line as well:

PROXY_SCHEMA = https

在最新版本的 Laravel forceSchema 方法名称已更改为 forceScheme,上面的代码应如下所示:

In latest version of laravel forceSchema method name has changed to forceScheme and the code above should look like this:

if (!empty($proxy_schema)) {
    URL::forceScheme($proxy_schema);
}