Http.redir - OR condition

Hello

i’m trying to redirect only certain “user agents” to https, others should stay on http.
here is what the config stanza ldea looks so far:

  redir 301 {
    if {>User-Agent} not_has "1-2-sports"
    / https://{host}{uri}
    if {>User-Agent} not_has "1-2-sports"
    / https://{host}{uri}
    if {>User-Agent} not_has "B.iCycle*"
    / https://{host}{uri}
    if {>User-Agent} not_has "iRun*"
    / https://{host}{uri}
    if {>User-Agent} not_has "iWalk*"
    / https://{host}{uri}
    if {>User-Agent} not_has "iSkate*"
    / https://{host}{uri}
}

but this is wrong, what i want is something like:

 redir 301 {
     if {>User-Agent} not_has "1-2-sports"
     or not_has "1-2-sports"
     or not_has "B.iCycle*"
     or not_has "iRun*"
     ...
     / https://{host}{uri}
 }

is something like this possible? was looking around the documentation but could not find anything.

danke =)

Hi @Herrmann_Hinz,

redir has an if_op subdirective which tells it how to chain conditionals. By default the operator is AND, but you can change it to OR.

The following example permanently redirects to example.com if the foo request header has either bar or xyz in it:

redir 301 {
  if_op or
  if {>foo} has bar
  if {>foo} has xyz
  / example.com
}

For statements like if {>User-Agent} not_has "B.iCycle*", though, you’ll want to use match to evaluate a regex string instead - not_has is a substring search and doesn’t do wildcards like *. Better still would be to wait for the not_starts_with conditional, which is still a substring search but anchored to the start of the string (much faster than regex).

Also, one other trap to look out for - multiple not_has in an OR chain would logically allow all requests through if the substrings you’re checking for are different;

redir 301 {
  if_op or
  if {>foo} not_has bar
  if {>foo} not_has xyz
  / localhost
}

# foo = bar; redirected to localhost (satisfies "not_has xyz" condition)
# foo = xyz; redirected to localhost (satisfies "not_has bar" condition)

https://caddyserver.com/docs/redir

1 Like

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