Redirect::permanent

Learn how to send permanent redirects in Axum using the Redirect::permanent method, understand the 308 status code, and avoid common browser caching pitfalls.

When a website moves to a new address, changes its domain, or restructures its URLs, users and search engines need to know how to get to the new location automatically. In web development, this is handled using HTTP redirects. Axum provides a straightforward tool for this purpose through the Redirect type, specifically the Redirect::permanent method, which signals that a resource has moved to a new location permanently.

What Redirect::permanent Does

Redirect::permanent is a method you call in your handler to construct a response that tells the client (like a web browser) to navigate to a different URL. It belongs to the Redirect struct in Axum's response module. When you return this from a handler, Axum sends an HTTP response with a 308 Permanent Redirect status code and a Location header containing the new URL.

308 Status Code:

The 308 status code is the modern standard for permanent redirects. It tells the browser, "The resource you asked for is gone forever. Please go to this new location instead. Keep using the same HTTP method you originally intended."

Before using this method, you need to understand the difference between a temporary and permanent redirect. A temporary redirect (Redirect::to) tells the browser, "This resource is temporarily somewhere else, try this new spot for now, but check the original spot again next time." A permanent redirect, which we cover here, tells the browser, "This resource has moved permanently. Update your bookmarks and search engine indexes. Never ask the original location again."

Starting with a Basic External Redirect

Let's begin with the simplest possible scenario. You have an old route in your application that should now point to an external website. For example, an old documentation link that points to a third-party site.

Here is a complete Axum application that redirects /old-home to https://example.com. The dependencies go in Cargo.toml:

# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
// main.rs
use axum::{
    response::Redirect,
    routing::get,
    Router,
};
async fn old_home() -> Redirect {
    Redirect::permanent("https://example.com")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/old-home", get(old_home));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

When you run this code and visit http://127.0.0.1:3000/old-home in your browser, the browser will instantly navigate to https://example.com. If you open your browser's developer tools and look at the Network tab, you will see the request to /old-home return a 308 Permanent Redirect status. The response will have a Location header set to https://example.com.

The mechanics here are simple. The handler function old_home returns a Redirect object. Axum sees this return type and automatically converts it into a proper HTTP response. The string "https://example.com" is the new location. Axum automatically places it in the Location header and sets the status to 308.

Using Internal Paths

Redirecting to a full external URL is straightforward, but often you need to redirect from one internal path to another within your own application. This happens when you restructure your API endpoints but need to keep old routes working for existing users.

In this case, you provide a relative path instead of a full URL. Axum accepts this and sets the Location header to that path.

// main.rs
use axum::{
    response::{Html, Redirect},
    routing::get,
    Router,
};
async fn old_blog_post() -> Redirect {
    Redirect::permanent("/new-blog/latest-post")
}
async fn new_blog_post() -> Html<&'static str> {
    Html("<h1>Welcome to the new blog location!</h1>")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/old-blog/my-post", get(old_blog_post))
        .route("/new-blog/latest-post", get(new_blog_post));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

Here, if a user visits /old-blog/my-post, they will be redirected to /new-blog/latest-post. The browser receives a Location: /new-blog/latest-post header and immediately makes a second request to that internal path. The address bar ends up showing the new URL and the user sees the new content.

This method is extremely useful for maintaining backwards compatibility. You can move your endpoints to more logical locations without breaking older clients or bookmarks.

Relative vs Absolute Paths:

When redirecting internally, always start the path with a / (e.g., /new-path). If you provide just "new-path" without the leading slash, the browser may interpret it as a relative path from the current URL. For example, a request to /old-blog/my-post redirecting to new-path would send the user to /old-blog/new-path, which is usually not what you want.

Why 308? Understanding Method Preservation

Historically, the standard for permanent redirects was the 301 Moved Permanently status code. While 301 is still widely used and supported, it has a significant behavioral quirk: browsers and HTTP clients often change the request method from POST to GET when they follow a 301 redirect.

To understand why this is a problem, think about a login form or an API endpoint. When a user submits a form, they send a POST request. If the server responds with a 301, the browser might automatically send the POST data as a GET request to the new location. This often results in the data being lost or the server rejecting the request.

The 308 Permanent Redirect status code was introduced to solve this. When a server returns 308, the client is instructed to repeat the exact same request (including the HTTP method and body) to the new location.

Axum's Redirect::permanent uses 308 precisely to ensure that your redirects do not accidentally break POST, PUT, or DELETE requests.

// Example handler that requires POST and returns a permanent redirect
use axum::{
    response::Redirect,
    routing::post,
    Router,
};
async fn submit_data() -> Redirect {
    // If this were a 301 redirect, the browser might turn this
    // into a GET request. 308 ensures it stays a POST.
    Redirect::permanent("/submissions/new-location")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/submit", post(submit_data));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

In this example, a POST request to /submit will redirect to /submissions/new-location while preserving the POST method. This is crucial for form submissions or APIs where changing the method would break the client's intent.

Using 301 Instead of 308:

If you need to use 301 for compatibility with very old clients or specific SEO requirements, you can construct it manually using Response::builder. However, for most modern applications, Redirect::permanent (which uses 308) is safer because it preserves the HTTP method. Relying on 301 for redirecting POST requests is a common source of hidden bugs.

Working with Dynamic Paths (Strings)

In real applications, the target of a redirect is rarely a hardcoded string literal. Often, you need to construct the new URL dynamically based on data from a path parameter or a database.

Redirect::permanent accepts a &str destination. This means you pass a string slice, or a reference to a String you built at runtime. It does not accept an owned String directly, and it does not accept a Uri.

Let's look at an example where we redirect from a user's old profile URL format to a new one.

// main.rs
use axum::{
    extract::Path,
    response::{Html, Redirect},
    routing::get,
    Router,
};
async fn old_user_profile(Path(user_id): Path<String>) -> Redirect {
    let new_url = format!("/users/{}/profile", user_id);
    Redirect::permanent(&new_url)
}
async fn new_user_profile(Path(user_id): Path<String>) -> Html<String> {
    Html(format!("<h1>Profile for user: {}</h1>", user_id))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/old-profile/{user_id}", get(old_user_profile))
        .route("/users/{user_id}/profile", get(new_user_profile));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

In this code, the old_user_profile handler extracts the user_id from the URL. It then uses the format! macro to create a new String that represents the new URL path. This String is then passed by reference, as &new_url, to Redirect::permanent.

A request to /old-profile/alice will receive a 308 redirect with Location: /users/alice/profile. The browser then makes a second request to /users/alice/profile, which displays "Profile for user: alice".

This approach is much more flexible than hardcoding strings because it allows your redirects to adapt to the specific user or content being accessed.

Common Mistakes and How to Fix Them

Redirects are simple on the surface, but they hide a few traps that can confuse beginners.

Browser Caching Permanent Redirects

The most common issue you will encounter when developing with Redirect::permanent is the browser's aggressive caching behavior.

When a browser receives a 308 Permanent Redirect, it may cache the mapping from the old URL to the new URL. This means that the next time you try to visit the old URL, the browser will skip the request to your server entirely and go straight to the new URL.

During development, this can be extremely frustrating. You might change the code to stop redirecting or redirect somewhere else, but the browser keeps sending you to the old target.

How to fix it:

  1. Use Incognito/Private Mode: The easiest way to test redirects is to do it in a private browsing window. Closing the window clears the cache.
  2. Clear Browser Cache: You can clear the browser's cache for your development site.
  3. Disable Cache (DevTools): In most browsers' Developer Tools (often under the Network tab), you can check a "Disable cache" option while the DevTools are open.

Debugging Redirect Loops:

If your redirect logic has a bug, you might create a redirect loop (A redirects to B, B redirects to A). Combined with browser caching, this can leave a user (or you, during testing) stuck. Always clear the cache or use incognito mode when you suspect a loop has been cached.

Forgetting the Absolute URL for External Sites

This is a very common mistake. If you want to redirect to an external website like Google, you must include the full scheme (http:// or https://).

use axum::response::Redirect;
// Wrong: this redirects to /www.google.com inside your own app!
async fn broken_external_redirect() -> Redirect {
    Redirect::permanent("www.google.com")
}
// Correct: this redirects to the external Google homepage
async fn working_external_redirect() -> Redirect {
    Redirect::permanent("https://www.google.com")
}

If you omit the scheme, Axum does not check or fix the string. It copies it into the Location header exactly as given, and the browser then resolves it as a relative path against the current URL. A redirect to "www.google.com" would result in the browser trying to find http://127.0.0.1:3000/www.google.com on your own server. This is usually not what you intend and often results in a 404 error.

Missing Scheme:

Always double-check your external redirect URLs. A missing https:// is a frequent source of broken links in production. The server will not throw an error; it will simply redirect to a local path that doesn't exist, leaving the user with a "Page Not Found" error on your domain.

Testing a Redirect::permanent Handler

Writing tests for your redirects is just as important as writing the handlers themselves. Axum integrates seamlessly with the tower ecosystem, allowing you to simulate HTTP requests and inspect responses without actually running a server.

Here is how you can write a test for a permanent redirect handler.

1

Step 1: Set up your project for testing

Ensure your Cargo.toml includes the necessary dev-dependency. You will need tower with the util feature, which provides the oneshot helper used below.

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
2

Step 2: Write the test module

Create a test module in your src/main.rs. The file below is complete: the handler, the small create_app helper, the main function, and the test module all live in the same file, so you can run it as it stands.

// src/main.rs
use axum::{
    response::Redirect,
    routing::get,
    Router,
};
async fn old_home() -> Redirect {
    Redirect::permanent("https://example.com")
}
fn create_app() -> Router {
    Router::new()
        .route("/old-home", get(old_home))
}
#[tokio::main]
async fn main() {
    let app = create_app();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}
#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use tower::ServiceExt;
    #[tokio::test]
    async fn test_permanent_redirect() {
        let app = create_app();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/old-home")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // Check the status code
        assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT);
        // Check the Location header
        let location = response.headers().get("Location").unwrap();
        assert_eq!(location, "https://example.com");
    }
}
3

Step 3: Run the test

Execute the test using cargo test. You should see the test pass, confirming that the handler returns the correct 308 status code and the Location header points to the intended URL.

The test creates a mock request to /old-home and passes it to the router using oneshot, which simulates a single client connection. The response object allows you to assert on its properties. Here, we are checking two things:

  1. The status() is StatusCode::PERMANENT_REDIRECT (which is 308).
  2. The headers() contain a Location header with the value https://example.com.

Redirects are Headers Only:

Notice that the test does not check the response body. Permanent redirects (and most HTTP redirects) typically do not include a body; they only require the Location header and the status code. The client (browser) is expected to simply navigate to the new location without rendering a page for the old one.

Summary

Choosing between a temporary and permanent redirect is a decision about long-term intent. Use Redirect::permanent when you are certain the old URL is retired forever - for example, after a domain migration, a site restructure, or fixing a stale API endpoint. The 308 status code it emits is critical for modern web applications because it protects non-GET requests like POST or DELETE from being silently converted to GET requests, which is a common failure mode with the older 301 status code.

The decision framework behind this page is short. Ask whether the old URL will ever come back. If the answer is no, and the move is final, use Redirect::permanent and accept that browsers and search engines will remember the new address. If the answer is yes or uncertain, a permanent redirect is the wrong tool, because undoing it means fighting cached mappings in browsers you do not control. And whenever the redirect must carry a form submission or an API call without changing its method, the 308 status is doing real work for you: it is the reason this constructor exists instead of the older 301, which silently turned those requests into GET calls.