简体   繁体   English

如何在单个 Laravel 应用程序中为多个域加载不同的 .env 文件?

[英]how to load different .env file for multiple domain in single laravel app?

I would like to access single laravel application by multiple domain.我想通过多个域访问单个 Laravel 应用程序。

For routing i have used laravel route pattern for eg.对于路由,我使用了 laravel 路由模式,例如。

$appRoutes = function() {
     Route::group(['namespace'=>"Interface1"], function(){

     /** route for index page and User authentication pages **/
     Route::get('/', 'LoginController@showLoginForm')->name('login'); 
 });
};

Route::group(array('domain' => 'example1.com'), $appRoutes);
Route::group(array('domain' => 'example2.com'), $appRoutes);

Now .env for each domain i have replaced config variable value inside AppServiceProvider.php register method:现在每个域的 .env 我已经替换了 AppServiceProvider.php 注册方法中的配置变量值:

   if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST']) ){ 
        if($_SERVER['HTTP_HOST']=='example1.com'){  
            $configArray = [
                'APP_NAME' => 'Application 1',
                'APP_URL'  =>  'http://example1.com', 
            ]; 
        }else{  
            $configArray = [
                'APP_NAME' => 'Application 2', 
                'APP_URL' =>  'http://example2.com, 
            ];  
        }  
        config($configArray);
    } 

but still i am not getting correct domain url using url(config('app.url'))但我仍然没有使用url(config('app.url'))获得正确的域 url

How to load all .env variable overwrite for each domain?如何为每个域加载所有.env变量覆盖?

config() sets the configuration settings but not the environment settings. config()设置配置设置,但不设置环境设置。

You have to do the following:您必须执行以下操作:

if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST']) ){ 
    if($_SERVER['HTTP_HOST']=='example1.com'){  
         $configArray = [
            'app.name' => 'Application 2', 
            'app.url' =>  'http://example2.com', 
        ];  ;
    }else{  
        $configArray = [
            'app.name' => 'Application 2', 
            'app.url' =>  'http://example2.com', 
        ];  
    }  
    config($configArray);
} 

You can then retrieve the values via:然后,您可以通过以下方式检索值:

config("app.name");
config("app.url");

As far as I know there is no way to modify the environment variables before the configuration is actually loaded, because the configuration is loaded and reads the environment variables before the service providers are registered.据我所知,在实际加载配置之前没有办法修改环境变量,因为在注册服务提供者之前加载配置并读取环境变量。

Also betware of using HTTP_HOST as it's a client-set header and may not be reliable.还要注意使用HTTP_HOST因为它是客户端设置的标头,可能不可靠。

For the current Laravel 7.x .对于当前的Laravel 7.x at the time of writing this, you can add the following code in your bootstrap/app.php file just before return $app statement.在撰写本文时,您可以在bootstrap/app.php文件中的return $app语句之前添加以下代码。

// bootstrap/app.php

// ...

/*
|-----------------------------------------------
| Load domain-specific .env file if it exists
|-----------------------------------------------
*/

if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])){
    $domain = $_SERVER['HTTP_HOST'];
}

if (isset($domain)) {
    $dotenv = Dotenv\Dotenv::createImmutable(base_path(), '.env.'.$domain);

    try {
        $dotenv->load();
    } catch (\Dotenv\Exception\InvalidPathException $e) {
        // No custom .env file found for this domain
    }
}

// ...

return $app;

Next, you should have a .env file for each domain in the following format .env.example1.com .env.example2.com .接下来,您应该为每个域创建一个.env文件,格式如下.env.example1.com .env.example2.com You can leave the original .env as a fallback for domains that lack an explicit .env file.您可以保留原始.env作为缺少明确.env文件的域的后备。

For Laravel 5.x or Laravel 6.x , you can find more from the original solution .对于 Laravel 5.x或 Laravel 6.x ,您可以从原始解决方案中找到更多信息。

A simple solution is here Laravel Multi Domain Package一个简单的解决方案是这里Laravel 多域包

This package allows a single Laravel installation to work with multiple HTTP domains.这个包允许单个 Laravel 安装使用多个 HTTP 域。

There are many cases in which different customers use the same application in terms of code but not in terms of database, storage and configuration.在很多情况下,不同的客户在代码方面使用相同的应用程序,但在数据库、存储和配置方面却没有。

This package gives a very simple way to get a specific env file, a specific storage path and a specific database for each such customer.这个包提供了一种非常简单的方法来为每个这样的客户获取特定的 env 文件、特定的存储路径和特定的数据库。

Installation steps安装步骤

Add gecche/laravel-multidomain as a requirement to composer.json:添加 gecche/laravel-multidomain 作为对 composer.json 的要求:

{
    "require": {
        "gecche/laravel-multidomain": "4.*"
    }
}

Update your packages with composer update or install with composer install.使用 composer update 更新您的软件包或使用 composer install 安装。

You can also add the package using composer require gecche/laravel-multidomain and later specify the version you want (for now, dev-v1.1.* is your best bet).您还可以使用 composer require gecche/laravel-multidomain 添加包,然后指定您想要的版本(目前,dev-v1.1.* 是您最好的选择)。

This package needs to override the detection of the HTTP domain in a minimal set of Laravel core functions at the very start of the bootstrap process in order to get the specific environment file.这个包需要在引导过程的一开始就在最小的 Laravel 核心函数集中覆盖 HTTP 域的检测,以获得特定的环境文件。 So this package needs a few more configuration steps than most Laravel packages.所以这个包比大多数 Laravel 包需要更多的配置步骤。

Installation steps:安装步骤:

replace the whole Laravel container by modifying the following lines at the very top of the bootstrap/app.php file.通过修改 bootstrap/app.php 文件最顶部的以下几行来替换整个 Laravel 容器。

//$app = new Illuminate\Foundation\Application(
$app = new Gecche\Multidomain\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

update the two application Kernels (HTTP and CLI).更新两个应用程序内核(HTTP 和 CLI)。 At the very top of the app/Http/Kernel.php file , do the following change:在 app/Http/Kernel.php 文件的最顶部,进行以下更改:

//use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Gecche\Multidomain\Foundation\Http\Kernel as HttpKernel;

Similarly in the app/Console/Kernel.php file:同样在 app/Console/Kernel.php 文件中:

//use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Gecche\Multidomain\Foundation\Console\Kernel as ConsoleKernel;

Override the QueueServiceProvider with the extended one in the $providers array in the config/app.php file:使用 config/app.php 文件中 $providers 数组中的扩展覆盖 QueueServiceProvider :

//Illuminate\Queue\QueueServiceProvider::class,
    Gecche\Multidomain\Queue\QueueServiceProvider::class,

publish the config file.发布配置文件。

php artisan vendor:publish 

Usage用法

This package adds three commands to manage your application HTTP domains:这个包添加了三个命令来管理您的应用程序 HTTP 域:

domain.add artisan command The main command is the domain:add command which takes as argument the name of the HTTP domain to add to the application. domain.add artisan 命令 主要命令是 domain:add 命令,它将 HTTP 域的名称作为参数添加到应用程序中。 Let us suppose we have two domains, site1.com and site2.com, sharing the same code.假设我们有两个域,site1.com 和 site2.com,共享相同的代码。

We simply do:我们只是这样做:

php artisan domain:add site1.com 

and

php artisan domain:add site2.com 

These commands create two new environment files, .env.site1.com and .env.site2.com, in which you can put the specific configuration for each site (eg databases configuration, cache configuration and other configurations, as usually found in an environment file).这些命令创建了两个新的环境文件,.env.site1.com 和.env.site2.com,您可以在其中放置每个站点的具体配置(例如数据库配置、缓存配置和其他配置,通常在一个环境中找到)文件)。

The command also adds an entry in the domains key in config/domains.php file.该命令还在 config/domains.php 文件中的域键中添加了一个条目。

In addition, two new folders are created, storage/site1_com/ and storage/site2_com/.此外,还创建了两个新文件夹:storage/site1_com/ 和 storage/site2_com/。 They have the same folder structure as the main storage.它们具有与主存储相同的文件夹结构。

Customizations to this storage substructure must be matched by values in the config/domain.php file.对此存储子结构的自定义必须与 config/domain.php 文件中的值匹配。

domain.remove artisan command The domain:remove command removes the specified HTTP domain from the application by deleting its environment file. domain.remove artisan 命令 domain:remove 命令通过删除其环境文件从应用程序中删除指定的 HTTP 域。 Eg:例如:

php artisan domain:remove site2.com 

Adding the force option will delete the domain storage folder.添加强制选项将删除域存储文件夹。

The command also removes the appropriate entry from, the domains key in config/domains.php file.该命令还会从 config/domains.php 文件中的域键中删除相应的条目。

domain.update_env artisan command The domain:update_env command passes a json encoded array of data to update one or all of the environment files. domain.update_env artisan 命令 domain:update_env 命令传递一个 json 编码的数据数组来更新一个或所有环境文件。 These values will be added at the end of the appropriate .env.这些值将添加到适当的 .env 的末尾。

Update a single domain environment file by adding the domain option.通过添加域选项更新单个域环境文件。

When the domain option is absent, the command updates all the environment files, including the standard .env one.当域选项不存在时,该命令会更新所有环境文件,包括标准的 .env 文件。

The list of domains to be updated is maintained in the domain.php config file.要更新的域列表保存在 domain.php 配置文件中。

Eg:例如:

php artisan domain:update_env --domain_values='{"TOM_DRIVER":"TOMMY"}' will add the line TOM_DRIVER=TOMMY to all the domain environment files. php artisan domain:update_env --domain_values='{"TOM_DRIVER":"TOMMY"}' 会将 TOM_DRIVER=TOMMY 行添加到所有域环境文件中。

domain.list artisan command The domain:list command lists the currently installed domains, with their .env file and storage path dir. domain.list artisan 命令 domain:list 命令列出了当前安装的域,以及它们的 .env 文件和存储路径目录。

The list is maintained in the domains key of the config/domain.php config file.该列表保存在 config/domain.php 配置文件的域键中。

This list is automatically updated at every domain:add and domain:remove commands run.此列表会在每次运行 domain:add 和 domain:remove 命令时自动更新。

config:cache artisan command The config:cache artisan command can be used with this package in the same way as any other artisan command. config:cache artisan 命令 config:cache artisan 命令可以像任何其他 artisan 命令一样用于这个包。

Note that this command will generate a file config.php file for each domain under which the command has been executed.请注意,此命令将为执行该命令的每个域生成一个文件 config.php 文件。 Ie the command即命令

php artisan config:cache --domain=site2.com 

will generate the file将生成文件

config-site2_com.php config-site2_com.php

Please visit the repository for more information请访问存储库以获取更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM