简体   繁体   中英

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

I would like to access single laravel application by multiple domain.

For routing i have used laravel route pattern for eg.

$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:

   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'))

How to load all .env variable overwrite for each domain?

config() sets the configuration settings but not the environment settings.

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.

For the current 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

// ...

/*
|-----------------------------------------------
| 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 . You can leave the original .env as a fallback for domains that lack an explicit .env file.

For Laravel 5.x or Laravel 6.x , you can find more from the original solution .

A simple solution is here Laravel Multi Domain Package

This package allows a single Laravel installation to work with multiple HTTP domains.

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.

Installation steps

Add gecche/laravel-multidomain as a requirement to composer.json:

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

Update your packages with composer update or install with 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).

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. So this package needs a few more configuration steps than most Laravel packages.

Installation steps:

replace the whole Laravel container by modifying the following lines at the very top of the bootstrap/app.php file.

//$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). At the very top of the app/Http/Kernel.php file , do the following change:

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

Similarly in the app/Console/Kernel.php file:

//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:

//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:

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. Let us suppose we have two domains, site1.com and site2.com, sharing the same code.

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).

The command also adds an entry in the domains key in config/domains.php file.

In addition, two new folders are created, storage/site1_com/ and 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.

domain.remove artisan command The domain:remove command removes the specified HTTP domain from the application by deleting its environment file. 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.

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. These values will be added at the end of the appropriate .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.

The list of domains to be updated is maintained in the domain.php config file.

Eg:

php artisan domain:update_env --domain_values='{"TOM_DRIVER":"TOMMY"}' will add the line TOM_DRIVER=TOMMY to all the domain environment files.

domain.list artisan command The domain:list command lists the currently installed domains, with their .env file and storage path dir.

The list is maintained in the domains key of the config/domain.php config file.

This list is automatically updated at every domain:add and domain:remove commands run.

config:cache artisan command The config:cache artisan command can be used with this package in the same way as any other artisan command.

Note that this command will generate a file config.php file for each domain under which the command has been executed. Ie the command

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

will generate the file

config-site2_com.php

Please visit the repository for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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