Skip to main content

Redirects

HTTP redirections

Actix 4.9+ 4 min read

# Redirects

Redirection instructs the client to go to a different URL.

#Using HttpResponse Builders

You can create redirects by setting the Location header and using a 3xx status code (usually 301 Permanent or 302/303 Temporary).

code_blocksrust
use actix_web::{get, HttpResponse, Responder};
use actix_web::http::header;

#[get("/old")]
async fn old_path() -> impl Responder {
    HttpResponse::Found() // 302
        .append_header((header::LOCATION, "/new"))
        .finish()
}

#Using web::Redirect

Actix Web provides a built-in helper for simple redirects.

code_blocksrust
use actix_web::web;
// in App config:
// .route("/old", web::get().to(|| async { web::Redirect::to("/new") }))

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{get, web, App, HttpServer, HttpResponse, Responder};
2use actix_web::http::header;
3
4#[get("/redirect")]
5async fn do_redirect() -> impl Responder {
6 HttpResponse::TemporaryRedirect()
7 .insert_header((header::LOCATION, "https://actix.rs"))
8 .finish()
9}
10
11#[actix_web::main]
12async fn main() -> std::io::Result<()> {
13 HttpServer::new(|| App::new().service(do_redirect))
14 .bind(("127.0.0.1", 8080))?
15 .run()
16 .await
17}
Was this page helpful?