How to redirect a.com/x/c to a.com/y/c in the URL

1. The problem I’m having:

Is there a way to have the browser show a uri replaced URL?

I have the url a.com/x/c and I want it always to be redirected to a.com/y/c (i.e. changing only /x to /y and leaving everything else intact.

The current Caddyfile works to change /x to /y:

a.com {
  uri replace /x /y
}

This works to show the correct page. However, when I do this and go to a.com/x/... seems that the browser URL still shows a.com/x/... when I go to that page (even though it correctly shows the page at a.com/y/...).

I guess there might be a combination of uri and redirect? I’m not sure how to use redirect with a uri replacement.

2. Error messages and/or full log output:

No error messages, because I can’t figure out the Caddyfile.

3. Caddy version:

v2.6.2 h1:wKoFIxpmOJLGl3QXoo6PNbYvGW4xLEgo32GPBEjWL8o=

4. How I installed and ran Caddy:

Using apt.

a. System environment:

Ubuntu 22

You can use the path_regexp matcher to capture the part you want to keep, then redir to perform the redirect.

@x path_regexp x ^/x(.*)
redir @x /y{re.x.1}
2 Likes

Thank you so much @francislavoie, that is an incredible snippet. It does exactly what I need and I would have never figured that out. Now that I see it though, it makes a lot of sense and is yet another cool example of what caddy can do!

2 Likes

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