Nono.MA

Load a Different .env for Each Domain to Support Multiple Domains in a Single Laravel Application

JULY 10, 2019

2020.04.01 Update · This code now works with Laravel 8.x and 7.x. (Code compatible with Laravel 5.x and 6.x can be also found below.)

It's convenient to deploy a single Laravel application and then point multiple domains to it and have different configurations (and databases) for each individual domain. This means that you can reuse your code and only deploy once if all of the websites share the same resources, and then just specify a custom .env environment file to configure each domain entry point.

The first thing you need to do is to add one .env per domain. (Leave your .env file as a default, which would be used as a fallback for domains where you haven't explicitly created a custom .env file.) For the domains you want to have their custom config, add a .env file attaching the domain name to the end of its filename, like .env.nono.ma, for instance.

Then add the following code to your bootstrap/app.php right before returning the $app.

// Laravel 8.x and 7.x
// 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;

Legacy code.

// Laravel 5.x and 6.x
// 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 ($domain) {
    $dotenv = \Dotenv\Dotenv::create(base_path(), '.env.'.$domain);
    try {
        $dotenv->overload();
    } catch (\Dotenv\Exception\InvalidPathException $e) {
        // No custom .env file found for this domain
    }
}

// ...

return $app;