Skip to content

Is there a way to redirect from www to non-www? #2707

Answered by iggyzuk
iggyzuk asked this question in Q&A
Discussion options

You must be logged in to vote

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

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(

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@iggyzuk
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by iggyzuk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants