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

JULY 10, 2019

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

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

I've tested this code with Laravel 5.8 and it works like a charm.