Mike Doe
Mike Doe

Reputation: 17566

Why .env should not be loaded in production in Symfony4?

The front controller index.php has by default:

// The check is to ensure we don't use .env in production
if (!isset($_SERVER['APP_ENV'])) {
    (new Dotenv())->load(__DIR__.'/../.env');
}

What's the reason behind this? Why .env file should be ignored in the production environment?

Upvotes: 2

Views: 3591

Answers (1)

kix
kix

Reputation: 3319

The idea behind .env is that it should be primarily used in development and testing environments, because in other environments such as a production or a staging web server you should be able to set up these variables externally. For example, Nginx allows you to use the env directive in your configuration files to set up variables the application will be able to pick up.

I think the reason why Symfony chose to treat .env this way is that it allows you to unify the way the variables for any runtime environment a developer might have. And also remember that in production deployments environment variables are first-class and quite common and do not change quite often.

Other thing here is security: server configurations are supposed to be more secure than your Symfony application's source code. E.g. as someone who has filesystem access to the app root on your prod server, you could steal database credentials if they are just stored in .env, but you won't be able to access those if they are kept somewhere securely in the server config, outside of the app root.

Anyways, if you are ready to take the risks of exposing your configuration on a production machine to everyone who has access to .env, you're still able to enable .env in your staging or production environment. To do that, you should remove or comment out these lines in index.php:

// Comment out the if statement so the code gets run every time:
// if (!isset($_SERVER['APP_ENV'])) {
    (new Dotenv())->load(__DIR__.'/../.env');
// }

Also, you'll have to move the DotEnv dependency from require-dev deps to require section in your composer.json:

{
    "type": "project",
    "license": "proprietary",
    "require": {
        ...
        "symfony/dotenv": "^4.0",
    ...
}

Upvotes: 5

Related Questions