为什么 .env 不应该在 Symfony4 的生产环境中加载?

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

前端控制器index.phphas by default:

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

这背后的原因是什么?为什么 .env 文件在生产环境中应该被忽略?

.env 背后的想法是,它应该主要用于 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,以便在配置文件中使用 env 指令来设置应用程序能够选择的变量向上。

我认为 Symfony 选择以这种方式对待 .env 的原因是它允许您统一开发人员可能拥有的任何运行时环境的变量方式。还要记住,在生产部署中,环境变量是第一个 class 并且很常见并且不会经常更改。

这里的另一件事是安全性:服务器配置应该比您的 Symfony 应用程序的源代码更安全。例如。作为对您的产品服务器上的应用程序根目录具有文件系统访问权限的人,如果它们仅存储在 .env 中,您可以窃取数据库凭据,但如果它们安全地保存在服务器配置,在应用根目录之外。

无论如何,如果您准备好冒险将生产机器上的配置暴露给有权访问 .env 的每个人,您仍然可以在暂存中启用 .env或生产环境。为此,您应该删除或注释掉 index.php:

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

此外,您必须将 DotEnv 依赖项从 require-dev deps 移动到 composer.json:

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