How to redirect / itself?

I am trying to redirect (302) from / to /en/. Just that.

I tried putting this in my config

http://127.0.0.1:8543 {
    redir / /en/ 302
}

But this redirects everything to /en/, including /en/ itself, causing a circular redirect:

$ curl -I http://127.0.0.1:8543/en/
HTTP/1.1 302 Found
Location: /en/

After some investigation I discovered it is in fact behaving as documented :

from is the request path to match (it must match exactly, except for /, which is a catch-all).

It’s seeing / as a catch-all, and so redirect everything to the target. However, I can’t work out any way to ask it to redirect just /. Is there any way to achieve this?

In the past I’ve used an if statement to double check the request was for / exactly.

I don’t have the config I used, but I believe something like this:

redir {
    / /en/ 302
    if {uri} is /
}

Should work (unless URI comes back as empty, I can’t remember right now). Worst case scenario you can check for if {request} ends_with your.domain.com/ to be super explicit about it and will definitely work.

You can find if statement docs currently in the rewrite directive documentation.

1 Like

Thanks. The solution I actually used was the one I found here:

https://github.com/mholt/caddy/issues/1427#issuecomment-279209976

But I do think the core behaviour in caddy should be revisited.

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