@@ -52,6 +52,7 @@ const DEFAULT_CAPACITY: usize = 65536;
5252#[ derive( Clone , Debug ) ]
5353pub struct ServeDir < F = DefaultServeDirFallback > {
5454 base : PathBuf ,
55+ prepend_path : String ,
5556 buf_chunk_size : usize ,
5657 precompressed_variants : Option < PrecompressedVariants > ,
5758 // This is used to specialise implementation for
@@ -72,6 +73,7 @@ impl ServeDir<DefaultServeDirFallback> {
7273
7374 Self {
7475 base,
76+ prepend_path : "" . to_string ( ) ,
7577 buf_chunk_size : DEFAULT_CAPACITY ,
7678 precompressed_variants : None ,
7779 variant : ServeVariant :: Directory {
@@ -88,6 +90,7 @@ impl ServeDir<DefaultServeDirFallback> {
8890 {
8991 Self {
9092 base : path. as_ref ( ) . to_owned ( ) ,
93+ prepend_path : "" . to_string ( ) ,
9194 buf_chunk_size : DEFAULT_CAPACITY ,
9295 precompressed_variants : None ,
9396 variant : ServeVariant :: SingleFile { mime } ,
@@ -115,6 +118,19 @@ impl<F> ServeDir<F> {
115118 }
116119 }
117120
121+ /// Sets a path to be prepended when performing a trailing slash redirect.
122+ ///
123+ /// This is useful when you want to serve the files at another location than "/", for example
124+ /// when you are using multiple services and want this instance to handle `/static/<path>`.
125+ /// In that example, you should pass in "/static" so that a trailing slash redirect does not
126+ /// redirect to `/<path>/` but instead to `/static/<path>/`
127+ ///
128+ /// The default is the empty string.
129+ pub fn prepend_path ( mut self , path : String ) -> Self {
130+ self . prepend_path = path;
131+ self
132+ }
133+
118134 /// Set a specific read buffer chunk size.
119135 ///
120136 /// The default capacity is 64kb.
@@ -211,6 +227,7 @@ impl<F> ServeDir<F> {
211227 /// ```
212228 pub fn fallback < F2 > ( self , new_fallback : F2 ) -> ServeDir < F2 > {
213229 ServeDir {
230+ prepend_path : "" . to_string ( ) ,
214231 base : self . base ,
215232 buf_chunk_size : self . buf_chunk_size ,
216233 precompressed_variants : self . precompressed_variants ,
@@ -358,6 +375,8 @@ impl<F> ServeDir<F> {
358375 }
359376 } ;
360377
378+ let prepend_path = self . prepend_path . clone ( ) ;
379+
361380 let buf_chunk_size = self . buf_chunk_size ;
362381 let range_header = req
363382 . headers ( )
@@ -375,6 +394,7 @@ impl<F> ServeDir<F> {
375394
376395 let open_file_future = Box :: pin ( open_file:: open_file (
377396 variant,
397+ prepend_path,
378398 path_to_file,
379399 req,
380400 negotiated_encodings,
0 commit comments