rust
44 lines · 7 steps
Building HTTP redirect handlers in Axum
Three Axum handlers turn legacy URLs into clean permanent redirects using path, query, and URI extractors.
Explained by
highlit
1use axum::{
2 extract::{Path, Query},
3 http::Uri,
4 response::{IntoResponse, Redirect},
5};
6use serde::Deserialize;
7
8#[derive(Deserialize)]
9pub struct LegacyArticleParams {
10 id: u64,
11}
12
13#[derive(Deserialize)]
14pub struct LegacyQuery {
15 #[serde(default)]
16 ref_source: Option<String>,
17}
18
19pub async fn redirect_legacy_article(
20 Path(params): Path<LegacyArticleParams>,
21 Query(query): Query<LegacyQuery>,
22) -> impl IntoResponse {
23 let mut target = format!("/articles/{}", params.id);
24 if let Some(source) = query.ref_source {
25 target.push_str(&format!("?utm_source={}", source));
26 }
27 Redirect::permanent(&target)
28}
29
30pub async fn redirect_trailing_slash(uri: Uri) -> impl IntoResponse {
31 let path = uri.path();
32 let trimmed = path.trim_end_matches('/');
33 let canonical = if trimmed.is_empty() { "/" } else { trimmed };
34
35 match uri.query() {
36 Some(q) => Redirect::permanent(&format!("{}?{}", canonical, q)),
37 None => Redirect::permanent(canonical),
38 }
39}
40
41pub async fn redirect_old_blog(Path(slug): Path<String>) -> impl IntoResponse {
42 let normalized = slug.to_lowercase().replace('_', "-");
43 Redirect::permanent(&format!("/posts/{}", normalized))
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Axum extractors like Path and Query deserialize request parts straight into typed structs for you.
- 2Permanent redirects (301) tell browsers and search engines the old URL has moved for good.
- 3Preserving query strings while rewriting paths keeps tracking params and canonical URLs intact.
Related explainers
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
rust
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::Path;
Parsing INI files in Rust
parsing
file-io
hashmap
Intermediate
9 steps
rust
use axum::{ body::Body, extract::MatchedPath, http::{Request, StatusCode},
An admin route guard in Axum middleware
middleware
authorization
request-extensions
Intermediate
7 steps
rust
use std::collections::VecDeque; pub struct RollingAverage { window: VecDeque<f64>,
A rolling average over a sliding window
sliding-window
running-sum
ring-buffer
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-http-redirect-handlers-in-axum-explained-rust-1a26/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.