Search code examples
http-redirectcaddycaddyfile

Redirect root "/" to uri with parameters


Im using caddy to pass some default querystring parameter to my application by redirecting it like so:

https://example.com/ --> https://example.com/?someQuery=someValue

The config I tried was

redir / {
    if {path} is /
    / /?someQuery=someValue
}

The problem with that approach is that it also matches the path with querystring and because of that will end up in a endless redirection loop.

How do only redirect it to the querystring URI if I didnt pass it the query values already (the uri without queries)?

Maybe Im just overlooking something.


Solution

  • Rather than testing against {path}, you can test against {uri} which includes the fragment and query.

    redir {
      if {uri} is /
      / /?someQuery=someValue
    }
    

    In this case, a request to /?someQuery=someValue would not produce a redirect.


    Alternately, you can simply add another if statement, checking for the query you plan to add:

    redir {
      if {path} is /
      if {query} not_has someQuery=someValue
      / /?someQuery=someValue
    }
    

    This will stop the redirect loop by stopping after the first one, although you're still ignoring the rest of the URI and will redirect away from other fragment and query information (which may be undesirable).