How to redirect to a different site using part of original URI?

Let’s say the browser accesses URL: mysite.com/hello/BLOB
I want to redirect that to another server: othersite.com/signup?param=BLOB

As you can see, the only common part part between those two is BLOB. I’ve tried fumbling around with if statements and regex without success. Can’t figure it out from documentation

I imagine it could look something like this, but it doesn’t work.

redir 307 {
r ^/hello/(.*)$
to http://othersite.com/signup?param={1}
}

Hi @mart, welcome to the Caddy community.

You’ve formatted your subdirectives like a rewrite, but redir uses a different syntax. redir doesn’t support dynamic locations in this manner. It does support request placeholders, though.

You might be able to cheat a little bit by using rewrite to format the entire URI before redirecting onwards. I’ve never personally tried this before, but give this a shot and see how you go:

# Rewrite using regex to format the URI to our desired result
rewrite {
	r ^/hello/(.*)$
	to /signup?param={1}
}
# Then send the whole rewritten URI to the destination
redir 307 {
	/ example.com{rewrite_uri}
}

https://caddyserver.com/docs/redir
https://caddyserver.com/docs/rewrite
https://caddyserver.com/docs/placeholders

There is also an interesting pull request that seems to be related:

https://github.com/mholt/caddy/pull/1750

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