Redir directory?

Is it possible to redirect an entire directory? E.g. redirect all requests to /foo/xxx to /bar/xxx or /bar/foo/xxx or anything.

I tried this and it doesn’t work at all:

:8080 {
    redir /foo/ /bar{path} 302

http.redir says about the from argument:

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

I assumed this means any path ending with /, but, no, it looks like root is special-cased. I’m trying to set up a stub site that just redirects to somewhere else with a fixed-up path. I thought I could use a rewrite combined with a redir to get what I wanted, but with redir so restricted it seems impossible…

In classic rubber-duck fashion I seem to have figured it out.

The key is to just embrace the / catch-all redirect and rewrites. Something like:

rewrite /foo {
    r (.*)
    to /bar{1}

redir /{rewrite_path}

This will rewrite requests to /foo/xyz to

Thanks for the great tool! This can be closed now. :slight_smile:

Hey @infogulch,

One trick I’ve used in the past is to make another site definition - you’re spot on with the “embrace the catch-all” statement, though:

:8080 {

:8080/foo {
  redir / /bar{uri}

This avoids abusing rewrite/regex checks and helps keep things neat, but it’s down to preference.


Ah i didn’t think about doing that. So in this case the /foo/xyz is caught by :8080/foo and redirects to /bar/xyz (because inside :8080/foo the root is at /foo/ not / so {uri} is /xyz), which is then caught by :8080. Is that correct?

It does avoid regex, but wouldn’t it cause a second request & round trip from the client? That seems more expensive than a regex to me. I guess it 301’s by default, so if the same client will request the same resource multiple times it might be worth it since the redirect will be aggressively cached.

In my case I ended up having a couple paths that needed more fixing up than just altering the top directory, and I expect many more new clients than repeat clients obviating the caching argument, so regex is probably my best bet.

Close. The {uri} is still actually /foo/xyz so it redirects to /bar/foo/xyz, but it is then indeed caught by the :8080 block.

It does, but as you say, it should be cached by the client - and you’re already doing one anyway:

So all we’re doing is cutting out the added regex.

If you want to serve different content without causing a second request, you want to rewrite and then not redirect at all. You can do that without a regex too, no site block required either:

# ->
rewrite /foo {
  to /bar{uri}

Cool. Thanks for the explanation! :slight_smile:

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