How to verify a header to validate an API key

No worries!

The trick is that you can combine the rewrite with something else, like status. These kinds of “rewrite hacks” enable some handy functionality in Caddy v1.

Something like this would work:

  rewrite {
    if {>X-API-Key} not {$API_KEY_ENV_VAR}
    to /forbidden
  }
  status 403 /forbidden

So we’re rewriting to a path we’re then explicitly instructing Caddy to issue an otherwise-empty 403 response for.

1 Like