Redirect::to

How to create temporary redirect responses in Axum using Redirect::to, with detailed examples, explanations, and common pitfalls.

When a user visits a URL that needs to move to another location, you can send back a special HTTP response that tells the browser to go to a different address. In Axum, the Redirect::to function builds exactly that kind of response for temporary moves. This page covers how to use it, what it does under the hood, and the situations where it fits.

What Redirect::to Does

Redirect::to returns a Redirect value that tells the browser to temporarily go to a new URL. The server answers the original request with an HTTP status code of 303 See Other and a Location header containing the destination address. The browser then automatically sends a new request to that destination, using GET.

Temporary means the move is not permanent. The old URL is expected to work again at some point, so browsers and search engines treat the response differently than a permanent redirect. Redirect::to is the right tool when you are making a short‑term change, like sending a user to a login page when they try to access a protected area.

The function is very simple to call. It takes a single argument: the destination URL as a &str. In practice, you almost always pass a string literal like "/dashboard" or "https://example.com". If you need a 307 Temporary Redirect instead, which preserves the request method and body, use Redirect::temporary, a separate constructor for that exact case.

A Minimal Working Example

Let's build the smallest possible Axum application that uses Redirect::to. Create a new project, add the dependencies, and put this code in src/main.rs. The serde dependency is only needed later on this page, for the example that reads a redirect target from the query string.

# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
use axum::{
    response::Redirect,
    routing::get,
    Router,
};
async fn old_page() -> Redirect {
    Redirect::to("/new-page")
}
async fn new_page() -> &'static str {
    "You arrived at the new page!"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/old-page", get(old_page))
        .route("/new-page", get(new_page));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run this program with cargo run. Then open a web browser and go to http://127.0.0.1:3000/old-page. You will not see a page that says "old page." Instead, the browser immediately shows "You arrived at the new page!" and the address bar changes to http://127.0.0.1:3000/new-page.

What happened behind the scenes? The handler old_page returned Redirect::to("/new-page"). Axum converted that into an HTTP response with status 303 and the header Location: /new-page. The browser saw that status, read the Location header, and made a fresh GET request to /new-page. That second request hit the new_page handler and produced the normal 200 OK response with the text.

Redirect is working correctly:

If you see the content of the target page and the URL in the address bar has changed, your redirect is functioning as intended. The browser followed the Location header automatically.

Understanding HTTP 303 and the Location Header

To use Redirect::to confidently, you need to know what the server is actually sending. The response has two important pieces:

  1. Status code 303 - This number belongs to the 3xx group of HTTP statuses, all of which mean "redirection". 303 specifically means "see other": the client should make a GET request to the new URL, even if the original request was a POST. That is a significant detail for forms or API calls.
  2. Location header - This header contains the destination URL as a string. The browser uses it to make the next request. It can be a relative path like /new-page or a full URL like https://example.com/new-page.

You can inspect the raw response using a tool like curl. If you run:

curl -i http://127.0.0.1:3000/old-page

You will see something like:

HTTP/1.1 303 See Other
location: /new-page
content-length: 0
date: Mon, 01 Jan 2024 12:00:00 GMT

There is no response body. The only thing the client needs is the status and the Location header. Axum automatically sets the body to empty when you return a Redirect.

Relative vs absolute URLs:

A Location value of /new-page is relative. The browser resolves it against the current origin (the same domain and port). If you use https://example.com/new-page, the redirect goes to a completely different website. Both are valid, but you should know which one you need.

Common Destinations in Practice

The destination string can be any valid URI. Here are several common patterns.

Relative paths within the same application

async fn profile_redirect() -> Redirect {
    Redirect::to("/user/settings")
}

This moves the user to a different route inside your own server. It is the most frequent use case for temporary redirects in web applications.

Absolute paths to an external site

async fn external_redirect() -> Redirect {
    Redirect::to("https://docs.rs/axum")
}

Sometimes you need to send users away from your site entirely - for example, to documentation or a third‑party login provider. Just pass the full URL.

Redirecting with a dynamic destination

You can build the destination string at runtime using any data available to the handler, such as path parameters or query strings.

use axum::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct RedirectQuery {
    next: Option<String>,
}
async fn login_redirect(Query(params): Query<RedirectQuery>) -> Redirect {
    // Default to the home page if no `next` query parameter was given.
    let destination = params.next.unwrap_or_else(|| "/".to_string());
    Redirect::to(&destination)
}

Here the handler reads a query string like ?next=/checkout. If the user visits /login?next=/checkout, they are redirected to /checkout after login. If no next parameter is supplied, they go to /. This is a very common pattern for returning users to the page they originally wanted.

Validate user‑supplied redirect targets:

When the destination comes from user input (query string, form field, etc.), do not blindly redirect to it. An attacker could craft a link like ?next=https://evil.example.com and trick users into leaving your site. Always check that the target is a relative path or a trusted domain before using it.

Using Redirect::to with Different Handler Return Types

Redirect::to returns a Redirect value, which already implements the IntoResponse trait. That means you can return it directly from a handler, as we have seen. But sometimes a handler may need to return either a redirect or some other response type (like a string) depending on the situation. For that, you can use impl IntoResponse as the return type.

use axum::response::{IntoResponse, Redirect};
async fn conditional_redirect() -> impl IntoResponse {
    // In a real handler this would come from a session check or similar.
    // It is computed inside the handler because a plain `bool` cannot be
    // a handler argument: handler arguments must be extractors.
    let logged_in = false;
    if logged_in {
        "Welcome back!".into_response()
    } else {
        Redirect::to("/login").into_response()
    }
}

In this example, the function returns impl IntoResponse, which allows it to return different concrete types as long as they all implement the trait. The into_response() method is called on each value to convert it into a common Response type. If you returned Redirect directly, you could not also return a string, because a function must have a single concrete return type.

Another situation is returning a Result where the error case is a redirect. For example:

use axum::response::{IntoResponse, Redirect};
async fn protected_page() -> Result<String, Redirect> {
    // Simulate checking whether the user is authenticated.
    let is_authenticated = false;
    if !is_authenticated {
        return Err(Redirect::to("/login"));
    }
    Ok("This is protected content.".to_string())
}

Here the successful response is a String, and the failure response is a Redirect. Axum knows how to convert both into a full HTTP response.

Redirect implements IntoResponse:

Because Redirect implements IntoResponse, you never need to call .into_response() when you return it directly from a handler. The function signature can be -> Redirect and Axum will handle the conversion automatically.

Adding Custom Headers to a Redirect

Sometimes a redirect alone is not enough - you may also need to attach extra headers, such as a cookie, a caching instruction, or a custom X-Request-ID. Redirect::to does not give you a way to add arbitrary headers. It only sets the Location header and the status code. For that level of control, you can build the response manually using Response::builder.

Here is how to create a temporary redirect with an extra header. Note the status used here is 307, not 303: this manual version preserves the request method, while Redirect::to uses 303 and switches the follow-up request to GET. Use Redirect::temporary if you want a 307 without building the response by hand.

use axum::{
    body::Body,
    http::{header, StatusCode},
    response::Response,
};
async fn redirect_with_header() -> Response {
    Response::builder()
        .status(StatusCode::TEMPORARY_REDIRECT)
        .header(header::LOCATION, "/new-page")
        .header("X-Custom-Header", "redirect-value")
        .body(Body::empty())
        .unwrap()
}

This manually constructs a response with status 307, the Location header, a custom header, and an empty body. It behaves like Redirect::temporary but gives you complete control.

Which one should you use? For the vast majority of redirects, Redirect::to is simpler and clearer. Only reach for the manual builder when you must add extra headers that Redirect::to cannot provide.

Do not mix Redirect with other response parts in a tuple:

You might be tempted to write something like (Redirect::to("/x"), header) to add a custom header. That will not compile because Redirect implements IntoResponse, not IntoResponseParts. IntoResponseParts is the trait needed for the leading elements of a response tuple. If you need custom headers with a redirect, use Response::builder as shown above.

Testing a Redirect Handler

In a real project you will want to verify that your redirect handler works correctly without manually opening a browser. Axum handlers can be tested with the tower::ServiceExt trait, which allows you to send a request directly to the router.

Here is a complete test that checks the status code and the Location header:

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::Body,
        http::{Request, StatusCode, header},
    };
    use tower::ServiceExt; // add `tower = { version = "0.5", features = ["util"] }` to dev-dependencies
    #[tokio::test]
    async fn redirect_sets_status_and_location() {
        let app = Router::new()
            .route("/old-page", get(old_page))
            .route("/new-page", get(new_page));
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/old-page")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        let location = response
            .headers()
            .get(header::LOCATION)
            .expect("Location header missing")
            .to_str()
            .unwrap();
        assert_eq!(location, "/new-page");
    }
}

This test confirms that the handler produces exactly the response a browser would receive: status 303 and Location: /new-page. You should also test that the destination is correct, especially when the redirect target is dynamic.

Relative Location values in tests:

When testing, response.headers().get(header::LOCATION) returns the exact string you passed to Redirect::to. If you passed a relative path like "/new-page", the header will be "/new-page". If you passed an absolute URL, it will be that full URL. Do not expect Axum to resolve relative paths into absolute URLs; that resolution happens in the browser, not on the server.

Common Beginner Mistakes

Several missteps happen repeatedly when people first use Redirect::to.

Returning a string instead of a Redirect

async fn wrong_redirect() -> &'static str {
    "/new-page"
}

This returns a normal 200 OK response with the body "/new-page". The browser will display that text on the screen. It will not redirect. You must return a Redirect value explicitly.

Forgetting that Redirect::to is temporary

Because the function name is just to, it is easy to assume it creates a permanent redirect. It does not. It creates a 303 See Other response, which is temporary and switches the follow-up request to GET. If you need a permanent redirect, Axum provides a separate Redirect::permanent function which uses status 308. If you need a temporary redirect that preserves the method, use Redirect::temporary, which uses status 307. Using the wrong one can confuse browsers and search engines about how to cache the redirect.

Trying to add a body to a redirect

Some people write code like this:

use axum::{http::StatusCode, response::IntoResponse};
async fn bad_redirect() -> impl IntoResponse {
    (StatusCode::TEMPORARY_REDIRECT, "You are being redirected")
}

This creates a response with status 307 and a body, but no Location header. The browser receives a redirect status but no destination, so it cannot follow the redirect and the navigation fails. A redirect response should have no body and must include the Location header. Redirect::to handles both of these for you.

Redirecting to an empty string

Redirect::to("") will produce a Location header with an empty value. Browsers interpret this as "redirect to the current URL," which can cause an infinite loop. Always provide a non‑empty destination.

If your test passes, you understand redirects correctly:

A passing test that checks for StatusCode::SEE_OTHER and the correct Location value is the clearest sign that you have mastered Redirect::to. It means you know what the server sends and how to verify it.

What Happens in the Browser Step by Step

Understanding the full sequence helps you debug redirect issues. When a user visits /old-page:

  1. The browser sends GET /old-page to your Axum server.
  2. Axum calls the old_page handler, which returns Redirect::to("/new-page").
  3. Axum converts that value into an HTTP response with status 303 and Location: /new-page. It sends this response back.
  4. The browser receives the response, sees status 303, and reads the Location header.
  5. The browser automatically sends a second request: GET /new-page.
  6. Axum calls the new_page handler, which returns a normal 200 OK response with the actual content.
  7. The browser displays that content and updates the address bar to /new-page.

If you use browser developer tools and look at the Network tab, you will see two requests: one for /old-page (with status 303) and one for /new-page (with status 200). The first response has no body.

When to Choose Redirect::to Over Manual Construction

Given that you can build any redirect manually with Response::builder, when should you use Redirect::to? The decision comes down to simplicity and clarity.

  • Use Redirect::to when all you need is a temporary redirect with a known destination. It is concise, impossible to forget the Location header, and communicates intent clearly.
  • Build the response manually when you also need to set extra headers (like cookies or cache controls) or when you want to include a body (rarely useful for redirects). In that case, the manual approach gives you full access to every part of the response.

Most handlers that redirect users after a form submission, after login, or after an action should use Redirect::to. It is the idiomatic choice in Axum for temporary redirects.

Summary

Redirect::to is the simplest way to send a temporary redirect from an Axum handler. It produces a 303 See Other with a Location header and an empty body. The browser follows the redirect automatically, so the user ends up at the new URL. Use it for any short‑term movement, such as sending unauthenticated users to a login page, redirecting after a successful POST, or guiding users to a new section of your site.

The key insight to remember is that Redirect::to is a convenience wrapper around a hand‑built response. It does nothing you could not do manually with Response::builder, but it saves you from forgetting the status code or the Location header. When you need extra headers or a different redirect status (like 308 Permanent Redirect), you can either use the manual builder or reach for Axum's other redirect helpers.

Decide by answering two questions about the move. First, is it temporary or permanent? A temporary move that may be undone calls for Redirect::to and its 303; a move that will never be undone calls for the permanent constructor and its 308. Second, must the follow‑up request keep the original method and body, as a form submission does? If yes, 303 is the wrong tool because it switches the follow‑up to GET, and you need the 307 constructor instead. If neither question changes your answer, Redirect::to is the default: short, hard to get wrong, and exactly what a browser expects for a short‑term move.