[variables] how to extract string from variables

1. The problem I’m having:

I want to extract the URL part without the “path” from the response header Location so that I can run another reverse_proxy to the redirect Link. But I don’t know if it is possible in Caddy, because it seems to me that the only way we can run some functions on string is to use expression but expression only return boolean.

Maybe my pseudo code like this will make things clearer

reverse_proxy https://commons.wikimedia.org {
          @redirect status 3xx
          vars redirHost func(regex({rp.header.Location}, "(http[s]:\/\/[a-zA-Z0-9-.])+(\/[a-zA-Z0-9-\/]+$)" ))[0]  # extract everything before path
          handle_response @redirect {
            reverse_proxy  {{vars.redirHost}}
          }
        }

3. Caddy version: 2.x

I think this would do the trick:

    reverse_proxy :8883 {
        @redirect status 3xx
        handle_response @redirect {
            @location vars_regexp location {rp.header.Location} (https?://)?([a-zA-Z0-9-.]+)(.*) 
            reverse_proxy @location {re.location.2} {
                rewrite {re.location.3}
            }
        }
    }

You can adjust the regexp as needed. Make sure you use Golang regexp syntax, you can use https://regex101.com/ to test it.

But I think you’re looking for a forward proxy here, not a reverse proxy. Wrong tool for the job. See Support Caddy 2 by mholt · Pull Request #74 · caddyserver/forwardproxy · GitHub

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