Skip to main content

axum/response/
redirect.rs

1use axum_core::response::{IntoResponse, IntoResponseParts, Response, ResponseParts};
2use http::{header::LOCATION, HeaderValue, StatusCode};
3
4/// Response that redirects the request to another location.
5///
6/// # Example
7///
8/// ```rust
9/// use axum::{
10///     routing::get,
11///     response::Redirect,
12///     Router,
13/// };
14///
15/// let app = Router::new()
16///     .route("/old", get(|| async { Redirect::permanent("/new") }))
17///     .route("/new", get(|| async { "Hello!" }));
18/// # let _: Router = app;
19/// ```
20#[must_use = "needs to be returned from a handler or otherwise turned into a Response to be useful"]
21#[derive(Debug, Clone)]
22pub struct Redirect {
23    status_code: StatusCode,
24    location: String,
25}
26
27impl Redirect {
28    /// Create a new [`Redirect`] that uses a [`303 See Other`][mdn] status code.
29    ///
30    /// This redirect instructs the client to change the method to GET for the subsequent request
31    /// to the given `uri`, which is useful after successful form submission, file upload or when
32    /// you generally don't want the redirected-to page to observe the original request method and
33    /// body (if non-empty). If you want to preserve the request method and body,
34    /// [`Redirect::temporary`] should be used instead.
35    ///
36    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303
37    pub fn to(uri: impl Into<String>) -> Self {
38        Self::with_status_code(StatusCode::SEE_OTHER, uri.into())
39    }
40
41    /// Create a new [`Redirect`] that uses a [`307 Temporary Redirect`][mdn] status code.
42    ///
43    /// This has the same behavior as [`Redirect::to`], except it will preserve the original HTTP
44    /// method and body.
45    ///
46    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307
47    pub fn temporary(uri: impl Into<String>) -> Self {
48        Self::with_status_code(StatusCode::TEMPORARY_REDIRECT, uri.into())
49    }
50
51    /// Create a new [`Redirect`] that uses a [`308 Permanent Redirect`][mdn] status code.
52    ///
53    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
54    pub fn permanent(uri: impl Into<String>) -> Self {
55        Self::with_status_code(StatusCode::PERMANENT_REDIRECT, uri.into())
56    }
57
58    /// Returns the HTTP status code of the `Redirect`.
59    #[must_use]
60    pub fn status_code(&self) -> StatusCode {
61        self.status_code
62    }
63
64    /// Returns the `Redirect`'s URI.
65    #[must_use]
66    pub fn location(&self) -> &str {
67        &self.location
68    }
69
70    // This is intentionally not public since other kinds of redirects might not
71    // use the `Location` header, namely `304 Not Modified`.
72    //
73    // We're open to adding more constructors upon request, if they make sense :)
74    fn with_status_code(status_code: StatusCode, uri: String) -> Self {
75        assert!(
76            status_code.is_redirection(),
77            "not a redirection status code"
78        );
79
80        Self {
81            status_code,
82            location: uri,
83        }
84    }
85}
86
87impl IntoResponse for Redirect {
88    fn into_response(self) -> Response {
89        (self, ()).into_response()
90    }
91}
92
93impl IntoResponseParts for Redirect {
94    type Error = (StatusCode, String);
95
96    /// Sets the redirect status code and `Location` header on the response.
97    ///
98    /// This allows `Redirect` to be used as part of a response tuple, for example
99    /// to include a body alongside a redirect as recommended by
100    /// [RFC 9110 ยง15.4.4](https://datatracker.ietf.org/doc/html/rfc9110#name-303-see-other).
101    ///
102    /// # Examples
103    ///
104    /// ```rust
105    /// use axum::response::{Html, Redirect};
106    ///
107    /// let url = "https://example.com";
108    ///
109    /// // Return a redirect with a body
110    /// let response = (
111    ///     Redirect::to(url),
112    ///     Html(format!(
113    ///         r#"<p>Redirecting to <a href="{url}">{url}</a></p>"#,
114    ///     )),
115    /// );
116    /// ```
117    ///
118    /// Note that when used alongside an explicit [`StatusCode`] in a tuple, the
119    /// `StatusCode` takes precedence:
120    ///
121    /// ```rust
122    /// use axum::response::Redirect;
123    /// use axum::http::StatusCode;
124    ///
125    /// // The status will be 307, not 303
126    /// let response = (
127    ///     StatusCode::TEMPORARY_REDIRECT,
128    ///     Redirect::to("/new"),
129    ///     "redirecting...",
130    /// );
131    /// ```
132    fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
133        match HeaderValue::try_from(self.location) {
134            Ok(location) => {
135                *res.status_mut() = self.status_code;
136                res.headers_mut().insert(LOCATION, location);
137                Ok(res)
138            }
139            Err(err) => Err((
140                StatusCode::INTERNAL_SERVER_ERROR,
141                format!("invalid redirect location: {err}"),
142            )),
143        }
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::Redirect;
150    use axum_core::response::IntoResponse;
151    use http::{header::LOCATION, StatusCode};
152
153    const EXAMPLE_URL: &str = "https://example.com";
154
155    // Tests to make sure Redirect has the correct status codes
156    // based on the way it was constructed.
157    #[test]
158    fn correct_status() {
159        assert_eq!(
160            StatusCode::SEE_OTHER,
161            Redirect::to(EXAMPLE_URL).status_code()
162        );
163
164        assert_eq!(
165            StatusCode::TEMPORARY_REDIRECT,
166            Redirect::temporary(EXAMPLE_URL).status_code()
167        );
168
169        assert_eq!(
170            StatusCode::PERMANENT_REDIRECT,
171            Redirect::permanent(EXAMPLE_URL).status_code()
172        );
173    }
174
175    #[test]
176    fn correct_location() {
177        assert_eq!(EXAMPLE_URL, Redirect::permanent(EXAMPLE_URL).location());
178
179        assert_eq!("/redirect", Redirect::permanent("/redirect").location())
180    }
181
182    #[test]
183    fn test_internal_error() {
184        let response = Redirect::permanent("Axum is awesome, \n but newlines aren't allowed :(")
185            .into_response();
186
187        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
188    }
189
190    #[test]
191    fn into_response_parts_sets_status_and_location() {
192        let response = (Redirect::to(EXAMPLE_URL), "body").into_response();
193
194        assert_eq!(response.status(), StatusCode::SEE_OTHER);
195        assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);
196    }
197
198    #[test]
199    fn into_response_parts_with_permanent_redirect() {
200        let response = (Redirect::permanent(EXAMPLE_URL), "body").into_response();
201
202        assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT);
203        assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);
204    }
205
206    #[test]
207    fn into_response_parts_with_temporary_redirect() {
208        let response = (Redirect::temporary(EXAMPLE_URL), "body").into_response();
209
210        assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);
211        assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);
212    }
213
214    #[test]
215    fn into_response_parts_explicit_status_overrides() {
216        // Explicit StatusCode in a tuple takes precedence over the Redirect status
217        let response = (
218            StatusCode::TEMPORARY_REDIRECT,
219            Redirect::to(EXAMPLE_URL),
220            "body",
221        )
222            .into_response();
223
224        assert_eq!(response.status(), StatusCode::TEMPORARY_REDIRECT);
225        assert_eq!(response.headers().get(LOCATION).unwrap(), EXAMPLE_URL);
226    }
227
228    #[test]
229    fn into_response_parts_invalid_location() {
230        let response = (Redirect::permanent("invalid\nlocation"), "body").into_response();
231
232        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
233    }
234}