DEV Community

Corey Alexander
Corey Alexander Subscriber

Posted on • Originally published at coreyja.com on

Fallback Routing with Axum

Yesterday I ran into a small problem with my Axum routing for my blog. So today I wanted to take 10 minutes and do quick write up about it!

My blog uses Axum as its Web Framework of choice. I was looking through some old emails and found one where a reader reached out about a post I made! (It was this one about FZF Spell Checking in VIM)

But I realized that it was linking to an older URL format, The link was to https://coreyja.com/blog/2018/11/10/vim-spelling-suggestions-fzf.html!

And you can see I was using a different URL structure then, and my current blog didn't have a redirect setup!

And that was our goal! I wanted https://coreyja.com/blog/2018/11/10/vim-spelling-suggestions-fzf.html to redirect to /posts/vim-spelling-suggestions-fzf. And I also decided that I wanted blog/anything-else-here to redirect to /posts

Simple enough!

I added these two routes to my Axum Router function:

.route("/blog/:year/:month/:date/:slug", get(redirect_to_new_post_url))
.route("/blog/*catchall", get(redirect_to_posts_index))
Enter fullscreen mode Exit fullscreen mode

And I expected this to work out of the box! But it didn't :sadnerd:

Instead I got an error about conflicting routes. Luckily the answer is relatively easy, at least in my case! I just needed to use nest to target all the /blog urls and then use a fallback. Here is what I ended up with!

.nest(
  "/blog",
  Router::new()
    .route("/:year/:month/:date/:slug", get(redirect_to_new_post_url))
    .fallback(redirect_to_posts_index)
)
Enter fullscreen mode Exit fullscreen mode

And now I was able to get all the redirects working as I wanted! Go check out that 'old' URL above now and with any luck you should be redirected to the right post!

Top comments (1)

Collapse
 
michaeltharrington profile image
Michael Tharrington

So siked to see your posts here again, Corey. Hope you've been doing well! šŸ™Œ