为同一服务器上的多个HTTP主机部署相同的Laravel代码库


Deploying the same Laravel codebase for multiple HTTP hosts on the same server

我在Laravel中编写了一个后端,需要在同一物理服务器上部署两次。我需要使用两个不同的数据库,但由于它们在同一台服务器上,我无法使用Laravel中内置的主机检测。

目前,我已经通过将我的配置文件包装在以下代码中"修复"了这个问题:

if ($_SERVER["HTTP_HOST"] === "example.com") {
    return config array...
} else if ($_SERVER["HTTP_HOST"] === "example.net") {
    return config array...
}

但这打破了artisan,所以不再有php artisan down|upphp artisan cache:clear

必须有更好的方法来实现这一点,不是吗?

默认情况下,正如您所说,Laravel使用您的主机名,但是您也可以将闭包传递给detectEnvironment方法,以使用更复杂的逻辑来设置环境。

像这样的东西,例如:

$env = $app->detectEnvironment(function()
{
    // if statements because staging and live used the same domain,
    // and this app used wildcard subdomains. you could compress this 
    // to a switch if your logic is simpler.
    if (isset($_SERVER['HTTP_HOST']))
    {
        if (ends_with($_SERVER['HTTP_HOST'], 'local.dev'))
        {
            return 'local';
        }
        if (ends_with($_SERVER['HTTP_HOST'], 'staging.server.com'))
        {
            return 'staging';
        }
        if (ends_with($_SERVER['HTTP_HOST'], 'server.com'))
        {
            return 'production';
        }
        // Make sure there is always an environment set.
        throw new RuntimeException('Could not determine the execution environment.');
    }
});

然而,这并不涉及artisan,HTTP_HOST不会设置在那里。如果不同的站点在不同的用户下运行,则可以使用$_SERVER['USER']执行另一个单独的switch语句。如果没有,您也可以使用安装路径来进行区分。