github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver
No package summary is available.
Package
Files: 6. Third party imports: 11. Imports from organisation: 1. Tests: 0. Benchmarks: 0.
Constants
Vars
BrowseTemplate is the default template document to use for file listings. By default, its default value is an embedded document. You can override this value at program start, or if you are running Caddy via config, you can specify a custom template_file in the browse configuration.
bufPool is used to increase the efficiency of file listings.
globSafeRepl replaces special glob characters with escaped equivalents. Note that the filepath godoc states that escaping is not done on Windows because of the separator.
Types
Browse
Browse configures directory browsing.
| Field name | Field type | Comment |
|---|---|---|
| TemplateFile |
|
Filename of the template to use instead of the embedded browse template. |
| RevealSymlinks |
|
Determines whether or not targets of symlinks should be revealed. |
| SortOptions |
|
Override the default sort. It includes the following options:
|
| FileLimit |
|
FileLimit limits the number of up to n DirEntry values in directory order. |
FileServer
FileServer implements a handler that serves static files.
The path of the file to serve is constructed by joining the site root
and the sanitized request path. Any and all files within the root and
links with targets outside the site root may therefore be accessed.
For example, with a site root of /www, requests to /foo/bar.txt
will serve the file at /www/foo/bar.txt.
The request path is sanitized using the Go standard library's path.Clean() function (https://pkg.go.dev/path#Clean) before being joined to the root. Request paths must be valid and well-formed.
For requests that access directories instead of regular files,
Caddy will attempt to serve an index file if present. For example,
a request to /dir/ will attempt to serve /dir/index.html if
it exists. The index file names to try are configurable. If a
requested directory does not have an index file, Caddy writes a
404 response. Alternatively, file browsing can be enabled with
the "browse" parameter which shows a list of files when directories
are requested if no index file is present. If "browse" is enabled,
Caddy may serve a JSON array of the directory listing when the Accept
header mentions application/json with the following structure:
[{
"name": "",
"size": 0,
"url": "",
"mod_time": "",
"mode": 0,
"is_dir": false,
"is_symlink": false
}]
with the url being relative to the request path and mod_time in the RFC 3339 format
with sub-second precision. For any other value for the Accept header, the
respective browse template is executed with Content-Type: text/html.
By default, this handler will canonicalize URIs so that requests to directories end with a slash, but requests to regular files do not. This is enforced with HTTP redirects automatically and can be disabled. Canonicalization redirects are not issued, however, if a URI rewrite modified the last component of the path (the filename).
This handler sets the Etag and Last-Modified headers for static files. It does not perform MIME sniffing to determine Content-Type based on contents, but does use the extension (if known); see the Go docs for details: https://pkg.go.dev/mime#TypeByExtension
The file server properly handles requests with If-Match, If-Unmodified-Since, If-Modified-Since, If-None-Match, Range, and If-Range headers. It includes the file's modification time in the Last-Modified header of the response.
| Field name | Field type | Comment |
|---|---|---|
| FileSystem |
|
The file system implementation to use. By default, Caddy uses the local disk file system. if a non default filesystem is used, it must be first be registered in the globals section. |
| Root |
|
The path to the root of the site. Default is Note that a site root is not a sandbox. Although the file server does sanitize the request URI to prevent directory traversal, files (including links) within the site root may be directly accessed based on the request path. Files and folders within the root should be secure and trustworthy. |
| Hide |
|
A list of files or folders to hide; the file server will pretend as if
they don't exist. Accepts globular patterns like Entries without a path separator ( When possible, all paths are resolved to their absolute form before comparisons are made. For maximum clarity and explictness, use complete, absolute paths; or, for greater portability, use relative paths instead. |
| IndexNames |
|
The names of files to try as index files if a folder is requested. Default: index.html, index.txt. |
| Browse |
|
Enables file listings if a directory was requested and no index file is present. |
| CanonicalURIs |
|
Use redirects to enforce trailing slashes for directories, or to remove trailing slash from URIs for files. Default is true. Canonicalization will not happen if the last element of the request's path (the filename) is changed in an internal rewrite, to avoid clobbering the explicit rewrite with implicit behavior. |
| StatusCode |
|
Override the status code written when successfully serving a file. Particularly useful when explicitly serving a file as display for an error, like a 404 page. A placeholder may be used. By default, the status code will typically be 200, or 206 for partial content. |
| PassThru |
|
If pass-thru mode is enabled and a requested file is not found, it will invoke the next handler in the chain instead of returning a 404 error. By default, this is false (disabled). |
| PrecompressedRaw |
|
Selection of encoders to use to check for precompressed files. |
| PrecompressedOrder |
|
If the client has no strong preference (q-factor), choose these encodings in order. If no order specified here, the first encoding from the Accept-Encoding header that both client and server support is used |
| precompressors |
|
No comment on field. |
| EtagFileExtensions |
|
List of file extensions to try to read Etags from. If set, file Etags will be read from sidecar files with any of these suffixes, instead of generating our own Etag. |
| fsmap |
|
No comment on field. |
| logger |
|
No comment on field. |
MatchFile
MatchFile is an HTTP request matcher that can match requests based upon file existence.
Upon matching, three new placeholders will be made available:
{http.matchers.file.relative}The root-relative path of the file. This is often useful when rewriting requests.{http.matchers.file.absolute}The absolute path of the matched file.{http.matchers.file.type}Set to "directory" if the matched file is a directory, "file" otherwise.{http.matchers.file.remainder}Set to the remainder of the path if the path was split bysplit_path.
Even though file matching may depend on the OS path separator, the placeholder values always use /.
| Field name | Field type | Comment |
|---|---|---|
| FileSystem |
|
The file system implementation to use. By default, the local disk file system will be used. |
| Root |
|
The root directory, used for creating absolute
file paths, and required when working with
relative paths; if not specified, |
| TryFiles |
|
The list of files to try. Each path here is
considered related to Root. If nil, the request
URL's path will be assumed. Files and
directories are treated distinctly, so to match
a directory, the filepath MUST end in a forward
slash |
| TryPolicy |
|
How to choose a file in TryFiles. Can be:
Default is first_exist. |
| SplitPath |
|
A list of delimiters to use to split the path in two
when trying files. If empty, no splitting will
occur, and the path will be tried as-is. For each
split value, the left-hand side of the split,
including the split value, will be the path tried.
For example, the path |
| fsmap |
|
No comment on field. |
| logger |
|
No comment on field. |
byName, byNameDirFirst, bySize, byTime
This type doesn't have documentation.
| Field name | Field type | Comment |
|---|---|---|
| type |
|
No comment on field. |
| type |
|
No comment on field. |
| type |
|
No comment on field. |
| type |
|
No comment on field. |
browseTemplateContext
browseTemplateContext provides the template context for directory listings.
| Field name | Field type | Comment |
|---|---|---|
| Name |
|
The name of the directory (the last element of the path). |
| Path |
|
The full path of the request. |
| CanGoUp |
|
Whether the parent directory is browsable. |
| Items |
|
The items (files and folders) in the path. |
| Offset |
|
If ≠0 then Items starting from that many elements. |
| Limit |
|
If ≠0 then Items have been limited to that many elements. |
| NumDirs |
|
The number of directories in the listing. |
| NumFiles |
|
The number of files (items that aren't directories) in the listing. |
| TotalFileSize |
|
The total size of all files in the listing. Only includes the size of the files themselves, not the size of symlink targets (i.e. the calculation of this value does not follow symlinks). |
| TotalFileSizeFollowingSymlinks |
|
The total size of all files in the listing, including the size of the files targeted by symlinks. |
| Sort |
|
Sort column used |
| Order |
|
Sorting order |
| Layout |
|
Display format (list or grid) |
| lastModified |
|
The most recent file modification date in the listing. Used for HTTP header purposes. |
crumb
crumb represents part of a breadcrumb menu, pairing a link with the text to display.
| Field name | Field type | Comment |
|---|---|---|
| Link |
|
No comment on field. |
fileInfo
fileInfo contains serializable information about a file or directory.
| Field name | Field type | Comment |
|---|---|---|
| Name |
|
No comment on field. |
| Size |
|
No comment on field. |
| URL |
|
No comment on field. |
| ModTime |
|
No comment on field. |
| Mode |
|
No comment on field. |
| IsDir |
|
No comment on field. |
| IsSymlink |
|
No comment on field. |
| SymlinkPath |
|
No comment on field. |
| Tpl |
|
a pointer to the template context is useful inside nested templates |
statusOverrideResponseWriter
statusOverrideResponseWriter intercepts WriteHeader calls to instead write the HTTP status code we want instead of the one http.ServeContent will use by default (usually 200)
| Field name | Field type | Comment |
|---|---|---|
|
No comment on field. | |
| code |
|
No comment on field. |
templateContext
templateContext powers the context used when evaluating the browse template. It combines browse-specific features with the standard templates handler features.
| Field name | Field type | Comment |
|---|---|---|
|
No comment on field. | |
|
No comment on field. |
Functions
func (*FileServer) FinalizeUnmarshalCaddyfile
FinalizeUnmarshalCaddyfile finalizes the Caddyfile parsing which requires having an httpcaddyfile.Helper to function, to setup hidden Caddyfiles.
Uses: filepath.Clean, strings.Contains.func (*FileServer) Provision
Provision sets up the static files responder.
Uses: encode.Precompressed, fmt.Errorf, strings.Contains.func (*FileServer) ServeHTTP
func (*FileServer) UnmarshalCaddyfile
UnmarshalCaddyfile parses the file_server directive. It enables the static file server and configures it with this syntax:
file_server [<matcher>] [browse] {
fs <filesystem>
root <path>
hide <files...>
index <files...>
browse [<template_file>]
precompressed <formats...>
status <status>
disable_canonical_uris
}
The FinalizeUnmarshalCaddyfile method should be called after this to finalize setup of hidden Caddyfiles.
Uses: caddyconfig.JSON, caddyhttp.WeakString, encode.Precompressed, strconv.Atoi.func (*MatchFile) Provision
Provision sets up m's defaults.
func (*MatchFile) UnmarshalCaddyfile
UnmarshalCaddyfile sets up the matcher from Caddyfile tokens. Syntax:
file <files...> {
root <path>
try_files <files...>
try_policy first_exist|smallest_size|largest_size|most_recently_modified
}
func (FileServer) CaddyModule
CaddyModule returns the Caddy module information.
func (MatchFile) CELLibrary
CELLibrary produces options that expose this matcher for use in CEL expression matchers.
Example:
expression file()
expression file({http.request.uri.path}, '/index.php')
expression file({'root': '/srv', 'try_files': [{http.request.uri.path}, '/index.php'], 'try_policy': 'first_exist', 'split_path': ['.php']})
Uses: caddyhttp.CELMatcherDecorator, caddyhttp.CELMatcherRuntimeFunction, caddyhttp.CELTypeJSON, caddyhttp.CELValueToMapStrList, caddyhttp.NewMatcherCELLibrary, caddyhttp.RequestMatcherWithError, cel.BoolType, cel.CustomDecorator, cel.EnvOption, cel.Function, cel.Macros, cel.ObjectType, cel.Overload, cel.ProgramOption, cel.SingletonBinaryBinding, cel.Type, parser.NewGlobalVarArgMacro, ref.Val.
func (MatchFile) CaddyModule
CaddyModule returns the Caddy module information.
func (MatchFile) Match
Match returns true if r matches m. Returns true if a file was matched. If so, four placeholders will be available:
- http.matchers.file.relative: Path to file relative to site root
- http.matchers.file.absolute: Path to file including site root
- http.matchers.file.type: file or directory
- http.matchers.file.remainder: Portion remaining after splitting file path (if configured)
func (MatchFile) MatchWithError
MatchWithError returns true if r matches m.
func (MatchFile) Validate
Validate ensures m has a valid configuration.
Uses: fmt.Errorf.func (browseTemplateContext) Breadcrumbs
Breadcrumbs returns l.Path where every element maps the link to the text to display.
Uses: strings.Repeat, strings.Split, url.PathUnescape.func (browseTemplateContext) HumanTotalFileSize
HumanTotalFileSize returns the total size of all files in the listing as a human-readable string in IEC format (i.e. power of 2 or base 1024).
Uses: humanize.IBytes.func (browseTemplateContext) HumanTotalFileSizeFollowingSymlinks
HumanTotalFileSizeFollowingSymlinks is the same as HumanTotalFileSize except the returned value reflects the size of symlink targets.
Uses: humanize.IBytes.func (byName) Len
func (byName) Less
func (byName) Swap
func (byNameDirFirst) Len
func (byNameDirFirst) Less
func (byNameDirFirst) Swap
func (bySize) Len
func (bySize) Less
func (bySize) Swap
func (byTime) Len
func (byTime) Less
func (byTime) Swap
func (fileInfo) HasExt
HasExt returns true if the filename has any of the given suffixes, case-insensitive.
Uses: slices.ContainsFunc, strings.HasSuffix, strings.ToLower.func (fileInfo) HumanModTime
HumanModTime returns the modified time of the file as a human-readable string given by format.
func (fileInfo) HumanSize
HumanSize returns the size of the file as a human-readable string in IEC format (i.e. power of 2 or base 1024).
Uses: humanize.IBytes.func (statusOverrideResponseWriter) Unwrap
Unwrap returns the underlying ResponseWriter, necessary for http.ResponseController to work correctly.
func (statusOverrideResponseWriter) WriteHeader
WriteHeader intercepts calls by the stdlib to WriteHeader to instead write the HTTP status code we want.
Private functions
func calculateEtag
calculateEtag computes an entity tag using a strong validator without consuming the contents of the file. It requires the file info contain the correct size and modification time. It strives to implement the semantics regarding ETags as defined by RFC 9110 section 8.8.3 and 8.8.1. See https://www.rfc-editor.org/rfc/rfc9110.html#section-8.8.3.
As our implementation uses file modification timestamp and size, note the following from RFC 9110 section 8.8.1: "A representation's modification time, if defined with only one-second resolution, might be a weak validator if it is possible for the representation to be modified twice during a single second and retrieved between those modifications." The ext4 file system, which underpins the vast majority of Caddy deployments, stores mod times with millisecond precision, which we consider precise enough to qualify as a strong validator.
References: strconv.FormatInt, strings.Builder.func celFileMatcherMacroExpander
func cmdFileServer
func fileHidden
fileHidden returns true if filename is hidden according to the hide list. filename must be a relative or absolute file system path, not a request URI path. It is expected that all the paths in the hide list are absolute paths or are singular filenames (without a path separator).
References: filepath.Match, strings.Contains, strings.HasPrefix, strings.Split, strings.TrimPrefix.func indexFold
There is no strings.IndexFold() function like there is strings.EqualFold(), but we can use strings.EqualFold() to build our own case-insensitive substring search (as of Go 1.14).
References: strings.EqualFold.func init
func isCELCaddyPlaceholderCall
isCELCaddyPlaceholderCall returns whether the expression is a caddy placeholder call.
References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, caddyhttp.CELPlaceholderFuncName.func isCELConcatCall
isCELConcatCall tests whether the expression is a concat function (+) with string, placeholder, or other concat call arguments.
References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, operators.Add.func isCELStringExpr
isCELStringExpr indicates whether the expression is a supported string expression
func isCELStringListLiteral
isCELStringListLiteral returns whether the expression resolves to a list literal containing only string constants or a placeholder call.
References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind.func isCELStringLiteral
isCELStringLiteral returns whether the expression is a CEL string literal.
References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, types.StringType.func isCELTryFilesLiteral
isCELTryFilesLiteral returns whether the expression resolves to a map literal containing only string keys with or a placeholder call.
References: ast.CallKind, ast.ComprehensionKind, ast.IdentKind, ast.ListKind, ast.LiteralKind, ast.MapKind, ast.SelectKind, ast.StructKind, ast.UnspecifiedExprKind, types.StringType.func isSymlink
isSymlink return true if f is a symbolic link.
References: os.ModeSymlink.func parseCaddyfile
parseCaddyfile parses the file_server directive. See UnmarshalCaddyfile for the syntax.
func parseErrorCode
parseErrorCode checks if the input is a status code number, prefixed by "=", and returns an error if so.
References: caddyhttp.Error, fmt.Errorf, strconv.Atoi.func parseTryFiles
parseTryFiles parses the try_files directive. It combines a file matcher with a rewrite directive, so this is not a standard handler directive. A try_files directive has this syntax (notice no matcher tokens accepted):
try_files <files...> {
policy first_exist|smallest_size|largest_size|most_recently_modified
}
and is basically shorthand for:
@try_files file {
try_files <files...>
policy first_exist|smallest_size|largest_size|most_recently_modified
}
rewrite @try_files {http.matchers.file.relative}
This directive rewrites request paths only, preserving any other part of the URI, unless the part is explicitly given in the file list. For example, if any of the files in the list have a query string:
try_files {path} index.php?{query}&p={path}
then the query string will not be treated as part of the file name; and if that file matches, the given query string will replace any query string that already exists on the request URI.
References: httpcaddyfile.ConfigValue, rewrite.Rewrite, strings.Index.func redirect
redirect performs a redirect to a given path. The 'toPath' parameter MUST be solely a path, and MUST NOT include a query.
References: http.Redirect, http.StatusPermanentRedirect, strings.HasPrefix, strings.TrimPrefix.func browseApplyQueryParams
browseApplyQueryParams applies query parameters to the listing. It mutates the listing and may set cookies.
References: http.Cookie, http.SetCookie.func directoryListing
func getEtagFromFile
Finds the first corresponding etag file for a given file in the file system and return its content
References: bytes.ReplaceAll, errors.Is, fmt.Errorf, fs.ErrNotExist, fs.ReadFile.func isSymlinkTargetDir
isSymlinkTargetDir returns true if f's symbolic link target is a directory.
References: caddyhttp.SanitizedPathJoin, fs.Stat, path.Join.func loadDirectoryContents
func makeBrowseTemplate
makeBrowseTemplate creates the template to be used for directory listings.
References: fmt.Errorf, path.Base, template.Template.func mapDirOpenError
mapDirOpenError maps the provided non-nil error from opening name to a possibly better non-nil error. In particular, it turns OS-specific errors about opening files in non-directories into os.ErrNotExist. See golang/go#18984. Adapted from the Go standard library; originally written by Nathaniel Caza. https://go-review.googlesource.com/c/go/+/36635/ https://go-review.googlesource.com/c/go/+/36804/
References: errors.As, errors.Is, fs.ErrInvalid, fs.ErrNotExist, fs.ErrPermission, fs.PathError, fs.Stat, strings.Join, strings.Split.func notFound
notFound returns a 404 error or, if pass-thru is enabled, it calls the next handler in the chain.
References: caddyhttp.Error, http.StatusNotFound.func openFile
openFile opens the file at the given filename. If there was an error, the response is configured to inform the client how to best handle it and a well-described handler error is returned (do not wrap the returned error value).
References: caddyhttp.Error, errors.Is, fs.ErrNotExist, fs.ErrPermission, http.StatusForbidden, http.StatusNotFound, http.StatusServiceUnavailable, strconv.Itoa, weakrand.Intn, zap.Error, zap.Int, zap.String, zapcore.DebugLevel.func serveBrowse
func transformHidePaths
transformHidePaths performs replacements for all the elements of fsrv.Hide and makes them absolute paths (if they contain a path separator), then returns a new list of the transformed values.
References: strings.Contains.func applySortAndLimit
func firstSplit
firstSplit returns the first result where the path can be split in two by a value in m.SplitPath. The return values are the first piece of the path that ends with the split substring and the remainder. If the path cannot be split, the path is returned as-is (with no remainder).
References: strings.HasPrefix.func selectFile
selectFile chooses a file according to m.TryPolicy by appending the paths in m.TryFiles to m.Root, with placeholder replacements.
References: caddyhttp.SanitizedPathJoin, filepath.Clean, filepath.ToSlash, fmt.Stringer, fs.Glob, fs.Stat, os.FileInfo, path.Clean, runtime.GOOS, strings.HasSuffix, strings.TrimPrefix, zap.Error, zap.String, zapcore.ErrorLevel.func strictFileExists
strictFileExists returns true if file exists and matches the convention of the given file path. If the path ends in a forward slash, the file must also be a directory; if it does NOT end in a forward slash, the file must NOT be a directory.
References: fs.Stat, strings.HasSuffix.Tests
Files: 3. Third party imports: 0. Imports from organisation: 0. Tests: 6. Benchmarks: 0.