how to redirct to another domain only with matched string in regex parentheses

I want to redirect http://localhost/somePath/xxxxxxx => http://www.example.com/xxxxxxx.

tried

redir {
    if {path} match ^/somePath/(.*)
    / http://www.example.com{uri}
}

and

localhost:80/somePath/ {
	redir / https://www.example.com/{uri}
}

They all take the page to https://www.example.com/somePath/xxxxxxx

expected: http://www.example.com/xxxxxxx
platform: windows 10
caddy version: 1.0.3

Anyone can help?

Hi @CoolRice, welcome to the Caddy community.

redir doesn’t support regex capture to get a redirection target.

You can rewrite first, though, and redir does support placeholders.

localhost:80 {
  rewrite /somePath/ {
    r ^/somePath(.+)$
    to {1}
  }
  redir {
    if {uri} starts_with /somePath
    if {rewrite_uri} not_starts_with /somePath
    / https://www.example.com{rewrite_uri}
  }
}

@Whitestrake, I tried you code, but got 404, did I miss something?

No, I missed something.

Just did some testing and the path that the regex is applied to is the URI after stripping the base path.

So the correct config would instead be:

localhost:80 {
  rewrite /somePath/ {
    r (.+)
    to {1}
  }
  redir {
    if {uri} starts_with /somePath
    if {rewrite_uri} not_starts_with /somePath
    / https://www.example.com{rewrite_uri}
  }
}
1 Like

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