From 39671d62e4232aefc888a14c20828f520a6f8fa7 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 17 Nov 2020 09:37:05 -0500 Subject: [PATCH] feat(http_of_dir): redirect to index.html if present --- src/bin/http_of_dir.ml | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/bin/http_of_dir.ml b/src/bin/http_of_dir.ml index 2f6bfd27..16ea4edd 100644 --- a/src/bin/http_of_dir.ml +++ b/src/bin/http_of_dir.ml @@ -7,6 +7,7 @@ type config = { mutable port: int; mutable upload: bool; mutable max_upload_size: int; + mutable auto_index_html: bool; mutable delete: bool; mutable j: int; } @@ -17,6 +18,7 @@ let default_config () : config = { delete=false; upload=false; max_upload_size = 10 * 1024 * 1024; + auto_index_html=true; j=32; } @@ -179,10 +181,17 @@ let serve ~config (dir:string) : _ result = S._debug (fun k->k "list dir %S (topdir %S)" full_path dir); let parent = Filename.(dirname path) in let parent = if parent <> path then Some parent else None in - let body = html_list_dir ~top:dir path ~parent in - S.Response.make_string - ~headers:[header_html; "ETag", Lazy.force mtime] - (Ok body) + if Sys.file_exists (full_path // "index.html") && config.auto_index_html then ( + let new_path = "/" // full_path // "index.html" in + S._debug (fun k->k "redirect to `%s`" new_path); + S.Response.make_raw ~code:301 "" + ~headers:S.Headers.(empty |> set "location" new_path) + ) else ( + let body = html_list_dir ~top:dir path ~parent in + S.Response.make_string + ~headers:[header_html; "ETag", Lazy.force mtime] + (Ok body) + ) ) else ( try let ic = open_in full_path in @@ -225,6 +234,8 @@ let main () = "--no-upload", Unit (fun () -> config.upload <- false), " disable file uploading"; "--max-upload", String (fun i -> config.max_upload_size <- parse_size i), " maximum size of files that can be uploaded"; + "--auto-index", Bool (fun b -> config.auto_index_html <- b), + " automatically redirect to index.html if present"; "--delete", Unit (fun () -> config.delete <- true), " enable `delete` on files"; "--no-delete", Unit (fun () -> config.delete <- false), " disable `delete` on files"; "-j", Int (fun j->config.j <- j), " maximum number of simultaneous connections";