tower-http icon indicating copy to clipboard operation
tower-http copied to clipboard

`ServeDir` does not redirect correctly for directories without trailing `/` when nested

Open Pistonight opened this issue 2 years ago • 4 comments

Bug Report

Version

tower-http v0.4.4

Platform

All

Description

This function redirects paths that don't end with / and is a directory to the URI with / appended https://github.com/tower-rs/tower-http/blob/e8eb54966604ea7fa574a2a25e55232f5cfe675b/tower-http/src/services/fs/serve_dir/open_file.rs#L253

However it does not take into account where the service could be nested, therefore producing an invalid redirect.

Example directory:

src/
├ main.rs
└ hello/
  └ index.html

main.rs:

use axum::{Router, Server};
use tower_http::services::ServeDir;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let serve_dir = ServeDir::new("src");
    let router = Router::new().nest_service("/src", serve_dir);

    let addr = "0.0.0.0:3000".parse().unwrap();

    Server::bind(&addr)
        .serve(router.into_make_service())
        .await
        .unwrap();

}

Going to localhost:3000/src/hello to see the issue Expected: Redirects to localhost:3000/src/hello/ and returns content at src/hello/index.html Actual: Redirects to localhost:3000/hello/ and returns Not Found

Pistonight avatar Sep 23 '23 19:09 Pistonight

Nesting is a concept of axum, not tower / tower-http. This is tracked at https://github.com/tokio-rs/axum/issues/1731.

jplatte avatar Nov 08 '23 09:11 jplatte

Unfortunately, this goes beyond axum. ServeDir generally doesn’t support being mounted into a subdirectory which limits its usefulness considerably. This can only be fixed by messing with the redirects produced by ServeDir which is quite frankly a very ugly hack.

palant avatar Apr 10 '24 18:04 palant

Yeah, I've thought a bunch about this in the meantime and I think it's probably much easier (and useful beyond axum) to add some prefix to ServeDir (maybe optionally stripping it from the input path, depending on whether you're already using sth. like nesting that does it up-front).

jplatte avatar Apr 11 '24 01:04 jplatte

I have created a PR: #486

claraphyll avatar May 01 '24 19:05 claraphyll