-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
--- | ||
title: Fallback Routing with Axum | ||
date: 2024-02-27 | ||
slug: 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](https://coreyja.com/posts/vim-spelling-suggestions-fzf/)) | ||
|
||
But I realized that it was linking to an older URL format, The link was to | ||
`https://coreyja.com/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: | ||
|
||
```rust | ||
.route("/blog/:year/:month/:date/:slug", get(redirect_to_new_post_url)) | ||
.route("/blog/*catchall", get(redirect_to_posts_index)) | ||
``` | ||
|
||
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! | ||
|
||
```rust | ||
.nest( | ||
"/blog", | ||
Router::new() | ||
.route("/:year/:month/:date/:slug", get(redirect_to_new_post_url)) | ||
.fallback(redirect_to_posts_index) | ||
) | ||
``` | ||
|
||
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! |