PHP env from external .env file?

I need to pass a lot of variables to PHP-FPM and looking for a way to implement it in some simple and efficient way.
As I understand from the documentation Caddy uses almost the same way as Nginx (I’m researching migration from Nginx actually) and relies on env directive.

My concern is that I already have .env file in my project with all variables (which are also used by other components) and it seems a bit inefficient to re-type the content of this file to Caddyfile and prefix each line with env directive.
I would like to have the single source of truth and such duplication seems not perfect.

So is there some way/hack/whatever to “load” PHP env variables from existing .env file (or just from current environment but without hardcode, as list of variables can be changed)?

You can load the env vars to Caddy with the --envfile argument for caddy run, and then you can add env VAR {$VAR} in the php_fastcgi subdirectives for each of them.

There’s no way to directly pass through all env vars. That would be bad. You’ll need to provide the list to Caddy to pass through.

Next time, please fill out the help topic template, as per the forum rules, so we can more precisely answer your question. I can’t suggest how to change how you run Caddy to provide the --envfile option because you didn’t tell us how you’re running Caddy.

Hi @francislavoie, thanks for looking into this
I apologize for not using your template, I relly didn’t know how it can be applicable here, as I don’t run Caddy, so almost any option could be ok to me

This it more like a research, as I’m getting tired of our legacy Nginx practices and overcomplicated config files and was looking for an alternative.
One of our pain points - inconcistency between Nginx conf and .env file (and also code duplicating), sometimes ppl just forget to add/update some parameter, what leads to false positive issues and wasting time. And since Nginx can’t use env variables at all - that’s getting even more complicated

Now I think such approach will not work at all, as we use not-isolated instances (so nginx.conf includes multiple sites config files and each site must use its own env file)

So it seems even with --envfile and rich API I can’t solve it with Caddy in some nice and clean way :frowning:

You can easily write a simple script to keep them in sync with sed and whatnot. I’m not sure I understand the issue.

Point is, with --envfile, you pass the values to Caddy, and then you use placeholders with {$VAR} to fill the values in the Caddyfile config.

It would be bad for security to pass through all environment variables to PHP transparently.

This topic was automatically closed after 30 days. New replies are no longer allowed.