black laptop computer turned on displaying blue screen

Laravel: Using Alternative .env Files Based on HTTP Host

Sometimes you need to use different environment configurations based on your host. Here’s a simple solution to achieve this in Laravel.

Implementation

Add the following code to your bootstrap/app.php file, before the return statement:


$envFile = '.env';
if (isset($_SERVER['HTTP_HOST']) && str_contains($_SERVER['HTTP_HOST'], 'alternativehost.test')) {
$envFile = '.env.althost';
}

🤓😎 More and more people are getting our Geek, Privacy, Dev & Lifestyle Tips

Want to receive the latest Geek, Privacy, Dev & Lifestyle blogs? Subscribe to our newsletter.

Want to let it work with php artisan as well in symlinked directories?


if (isset($_SERVER['PWD']) && str_contains($_SERVER['PWD'], '/alternativehost')) {
$envFile = '.env.althost';
}

This is probably dangerous. Check warnings below.

How It Works

The code checks two conditions:

  1. First, it checks if the HTTP host contains your specified domain (safer approach)
  2. Second, it checks the working directory path (riskier approach, but useful for CLI operations)

⚠️ Important Notes

  • The second condition using PWD is riskier as it relies on directory structure and might need additional security measures
  • Always ensure your alternative .env files are included in your .gitignore
  • Remember to clear config cache after making changes:
    php artisan config:clear

Best Practices

  • Keep your .env files secure and never commit them to version control
  • Use descriptive names for your alternative .env files
  • Document the environment differences for your team
  • Consider using Laravel’s built-in environment detection when possible

Last Updated on 5 March 2025

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish
Scroll to Top