Actix-web: feature request: StaticFiles::index_file without redirect

Created on 19 Oct 2018  路  7Comments  路  Source: actix/actix-web

I prefer to have my main URL "clean" (without /index.html) but something like index_file (without a redirect) would be simpler than using default_handler with NamedFile.

C-improvement P-files

Most helpful comment

JFYI This is planned for 0.8 in my PR on refactoring of Static Files. since it is breaking change.

All 7 comments

I had the same issue, this is my solution:

    .resource("/", {
        let frontend_dir_ = frontend_dir.clone();
        move |r| r.f(move |_r| -> Result<fs::NamedFile> {
            Ok(fs::NamedFile::open(frontend_dir_.join("index.html"))?)
        })
    })
    .handler("/", fs::StaticFiles::new(&frontend_dir).unwrap())

I think since this is a common use case (e.g. for single page web apps), it makes sense to have this in actix-web, e.g.:

.handler("/", 
    fs::StaticFiles::new(&frontend_dir).unwrap().transparent_index_file("index.html")
)

(Transparent serving instead of redirecting.)

What type is front end dir above, I can't get it working.

Okay I found the right way to do this:

      .resource("/favicon.ico", |r| r.f(favicon))
      .resource("/", |r| r.f(index))
      .handler(
        "/static",
        fs::StaticFiles::new("../ui/dist/")
          .unwrap()
          // .index_file("index.html"),
      )
      .finish()

And the methods can look like:

fn index(_req: &HttpRequest) -> Result<NamedFile, actix_web::error::Error> {
  Ok(NamedFile::open("../ui/dist/index.html")?)
}

fn favicon(_req: &HttpRequest) -> Result<NamedFile, actix_web::error::Error> {
  Ok(NamedFile::open("../ui/src/favicon.ico")?)
}

JFYI This is planned for 0.8 in my PR on refactoring of Static Files. since it is breaking change.

@dessalines frontend_dir is a PathBuf above. I use an env var to set it:

let frontend_dir = PathBuf::from(env::var("FRONTEND_DIR").expect("FRONTEND_DIR"));

Because on my laptop, I have it set to FRONTEND_DIR=target/deploy in my .env file (btw, for most env vars I usually use envy), and then I build my wasm frontend to that dir with cargo web deploy, and in production, I set it to a separate dir.

@DoumanAsh can we close this?

Yes, it is in 1.0

Was this page helpful?
0 / 5 - 0 ratings