-
SummaryI want to force non-www for my website e.g. https://www.example.com/hey -> https://example.com/hey axum version0.7.4 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Are you talking about a case where requests to both go to the same axum server? I'd usually do this one level higher at the nginx or whatever reverse proxy you have in front that also does TLS termination. If you don't have one at all and are receiving TLS traffic directly (e.g. via |
Beta Was this translation helpful? Give feedback.
-
In case anyone is looking for the code. pub async fn redirect_to_non_www(request: Request, next: Next) -> Result<impl IntoResponse, AppError> {
let host = request.headers().get("host").and_then(|h| h.to_str().ok());
if let Some(host) = host {
if host.starts_with("www.") {
let uri = request.uri().clone();
let mut parts = uri.into_parts();
parts.scheme = Some(Scheme::HTTPS);
parts.authority = Some(http::uri::Authority::from_str(
host.trim_start_matches("www."),
)?);
let new_uri = http::Uri::from_parts(parts)?;
let response = Response::builder()
.status(StatusCode::MOVED_PERMANENTLY)
.header("Location", new_uri.to_string())
.body(Body::empty())?;
return Ok(response);
}
}
Ok(next.run(request).await)
} |
Beta Was this translation helpful? Give feedback.
In case anyone is looking for the code.
Add it to the
Router
with:app.layer(axum::middleware::from_fn(redirect_to_non_www))
AppError
is like in example: https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs