Rewrite based on “time”

I know caddy allows conditional rewrites. I’m looking to perform a rewrite based on current time. Is that possible? If so, what is the syntax?

Essentially I would like to rewrite/redir a request if it happens to be a certain time.

My Caddy Config

:80 {
    reverse_proxy /proxypath 192.168.1.171:8000 {
        @404 status 404
        handle_response @404 {
            redir /* /newproxypath
        }
    }
}

This works, but it only redirects based on the upstream status code. I’d like to include an “if” matcher that will only redirect at certain times of the day. I found this post but it’s from 2017 so I’d imagine a lot has changed since then. But accordign to it, it would be somethin like this.

redir 301 {
    if {current_time} = 6-7UTC
    /* /newproxypath
}

Caddy Version = 2.7.6
Installed Using = Built from source using xcaddy on FreeBSD

Please fill out the help topic template as per the forum rules.

Your question is lacking context. Show examples of what you want to perform. We can’t read your mind. Please show specifics.

My apologies. Post edited.

There’s no existing matcher to operate on time. You might be able to hack something together using a time placeholder and a CEL expression, but I think the best way to go is to write a plugin to do exactly what you need. Doing time math is non-trivial especially due to leap years and leap seconds and whatnot, so just a CEL expression on the integer epoch seconds is probably not viable to get a range of hours.

Hmmm…

For now I sort of hacked it by redirecting both paths to each other. Basically I’m setting up a stream that should redirect to /stream at certain times of the day, but redirect to /recording.mp3 the rest of the time.

For now I did this…

 reverse_proxy /stream 192.168.1.171:8000 {
     @404 status 404
     handle_response @404 {
         redir /* /recording.mp3
     }
}
reverse_proxy /recording.mp3 192.168.1.171:8000  {
     @404 status 404
     handle_response @404 {
         redir /* /stream
     }
}

This essentially redirects to the stream if the file is not present, and to the file if the stream is not present. When the stream goes live, it will work with either path. It’s hacky but that’s the best I have right now.

Would a rewrite here be more efficient?
Is there a way to tell caddy to only rewrite a certain number of times?

I actually like the idea of a time based matcher. I almost wrote one with Caddy 2 back in 2020 but decided not to since I couldn’t think of a use case and there’s a lot of ways to do it, I’d want to make sure it was useful first.

I think this would be fun to make. I might build a separate plugin to do this.

1 Like

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