Redirect to another host if 404

(Pontus) #1

Hey,

I want to have caddy redirect to a URL with a different host if the host goes down or is under maintenance.

I’m new to caddy, and can’t claim much expertise in the field in general. I have tried searching the examples and this forum, but I haven’t been able to find an answer. I’ve given it a couple of hours now, but the -validate always fails…

I’ve tried some options along the lines of…
`status 404 {
URL
}

…with rewrite and redirect.

I could show the full examples, but I suspect I’d just look like a fool :slight_smile:

Is there a way to configure this? Any help with be much appreciated…

(b2c) #2

Hello @Pontus, I’m also new here. :grinning:

You can rewrite to not-found if URL doesn’t exist;

rewrite {
	to {path} {path}/ /not-found
}

https://caddyserver.com/docs/rewrite

After that, you can redirect this to new host;

redir /not-found https://newsite.com 301

https://caddyserver.com/docs/redir

1 Like
(Pontus) #3

Thanks for your reply @b2c!

I’m not quite sure how to structure it though. I’ve tried a number of variants along the lines of:

main-url {
    root /path/to/build
    rewrite {
         if status is 404 to /not-found
         redir /not-found optional-url 301
    }
}

This particular result is Error during parsing: Wrong argument count or unexpected line ending after '/not-found', but I tried a variety of different structures and syntax. Any idea?

(b2c) #4

Try this, you need to replace url/path/port etc.

main-url:port {
    root /path/to/build 

	rewrite {
		to {path} {path}/ /not-found
    }

    redir /not-found https://newsite.com 301 
}
2 Likes