We are in the process of reworking a Symfony5 application to Symfony6. We have a special case where the environment APP_ENV is dependent on the hostname of the app.
Accessing the same app via app1.domain.com and app2.domain.com should set the APP_ENV variable for symfony to prod1 or prod2.
This used to happen in the config/bootstrap.php (a relic from Symfony4), but this is no longer available in Symfony6.
Where is the best update-save place to inject some code to switch the variable before Symfony starts processing requests?
The old portion in bootstrap.php looked something like this:
if(isset($_SERVER['HTTP_HOST'])) {
if(preg_match('#^app1.domain.com$#',$_SERVER['HTTP_HOST'])) {
$_SERVER['APP_ENV'] = "prod1"; $_ENV['env_name'] = "prod1";
$_ENV['env_name'] = "production_client1";
} elseif(preg_match('#^app2.domain.com$#',$_SERVER['HTTP_HOST'])) {
$_SERVER['APP_ENV'] = "prod2"; $_ENV['env_name'] = "prod2";
$_ENV['env_name'] = "production_client2";
} elseif(preg_match('#^app.dev.local$#',$_SERVER['HTTP_HOST'])) {
$_SERVER['APP_ENV'] = "dev"; $_ENV['env_name'] = "dev";
$_ENV['env_name'] = "development";
} else {
die("invalid domain");
}
}
Further switching happens within the app depending on the environment.
The following approaches do/did NOT work:
- setting the environment variable on the server (shared hosting) is not possible
- setting it via .htaccess does not work because mod_rewrite prepends REDIRECT_ to all environment variables
- subscribers/listeners only attach at the request event (kernel.request), which is too late
- setting it in .env is static
- setting it in .env.local.php is not update save, as this file is generated
- running a file as a imported resource (imports) in config.yaml is also does not seem to work
This question is explicitly about switching the environment, not necessarily about a workaround! A nice bonus feature of this was that the same code could be run in the dev environment on the server just by accessing it via the local dev domain.
2
Answers
The solution we went with was to put the switching code into an include file in config/ and load it directly from index.php before loading autoload_runtime.php and before creation of the kernel. Thank you to @Cerad for ensuring us that this would probably be ok.
You can use individual environment tweaks depending on the host. For example, choose the right database or other settings for the Symfony app without cloning it for each host.
You can also manage these configurations from another application, you can create a control panel for these settings. Like a hostprovider)
Just update index.php (Symfony 6.2)
Enjoy!