Evaluate a conditional based on an environment variable

Can Caddy syntax evaluate a conditional based on a environment variable?

For example:

if( {$DEV} === true ) {
    root /var/www/dev

The environment variable $DEV is equal to true.

No, the Caddyfile is not really programmable. (And that’s how I like it, personally.)

I’m bending my own preferences a bit with this PR: https://github.com/mholt/caddy/pull/1948

If that PR gets merged, then what you want to do may be possible, but I am not sure if it will work properly.

For now, and even in the future, probably better to set an environment variable containing the value of your root path: root {$SITE_ROOT} or something.

1 Like

You could use if functionality of existing directives like redir and rewrite, though, as env vars can be used in place of any Caddyfile token: The Caddyfile — Caddy Documentation

For example, this should effectively serve your site from /var/www/dev when DEV=true in your environment, and will serve from /var/www/prod otherwise:

root /var/www
rewrite {
  if {$DEV} is true
  to /dev{uri}
rewrite {
  if {$DEV} not true
  to /prod{uri}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.