DEV Community

Corey Alexander
Corey Alexander Subscriber

Posted on ā€¢ Originally published at coreyja.com on

2 2 1 2 1

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!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (1)

Collapse
 
michaeltharrington profile image
Michael Tharrington ā€¢

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

šŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay