fileserver

package
v2.0.0-...-08fb5b1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2023 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Browse

type Browse struct {
	// Use this template file instead of the default browse template.
	TemplateFile string `json:"template_file,omitempty"`
}

Browse configures directory browsing.

type FileServer

type FileServer struct {
	// The file system implementation to use. By default, Caddy uses the local
	// disk file system.
	//
	// File system modules used here must adhere to the following requirements:
	// - Implement fs.FS interface.
	// - Support seeking on opened files; i.e.returned fs.File values must
	//   implement the io.Seeker interface. This is required for determining
	//   Content-Length and satisfying Range requests.
	// - fs.File values that represent directories must implement the
	//   fs.ReadDirFile interface so that directory listings can be procured.
	FileSystemRaw json.RawMessage `json:"file_system,omitempty" caddy:"namespace=caddy.fs inline_key=backend"`

	// The path to the root of the site. Default is `{http.vars.root}` if set,
	// or current working directory otherwise. This should be a trusted value.
	//
	// 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.
	Root string `json:"root,omitempty"`

	// A list of files or folders to hide; the file server will pretend as if
	// they don't exist. Accepts globular patterns like `*.ext` or `/foo/*/bar`
	// as well as placeholders. Because site roots can be dynamic, this list
	// uses file system paths, not request paths. To clarify, the base of
	// relative paths is the current working directory, NOT the site root.
	//
	// Entries without a path separator (`/` or `\` depending on OS) will match
	// any file or directory of that name regardless of its path. To hide only a
	// specific file with a name that may not be unique, always use a path
	// separator. For example, to hide all files or folder trees named "hidden",
	// put "hidden" in the list. To hide only ./hidden, put "./hidden" in the list.
	//
	// 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.
	Hide []string `json:"hide,omitempty"`

	// The names of files to try as index files if a folder is requested.
	// Default: index.html, index.txt.
	IndexNames []string `json:"index_names,omitempty"`

	// Enables file listings if a directory was requested and no index
	// file is present.
	Browse *Browse `json:"browse,omitempty"`

	// 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.
	CanonicalURIs *bool `json:"canonical_uris,omitempty"`

	// 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.
	StatusCode caddyhttp.WeakString `json:"status_code,omitempty"`

	// 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).
	PassThru bool `json:"pass_thru,omitempty"`

	// Selection of encoders to use to check for precompressed files.
	PrecompressedRaw caddy.ModuleMap `json:"precompressed,omitempty" caddy:"namespace=http.precompressed"`

	// 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
	PrecompressedOrder []string `json:"precompressed_order,omitempty"`
	// contains filtered or unexported fields
}

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.

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.

func (FileServer) CaddyModule

func (FileServer) CaddyModule() caddy.ModuleInfo

CaddyModule returns the Caddy module information.

func (*FileServer) Provision

func (fsrv *FileServer) Provision(ctx caddy.Context) error

Provision sets up the static files responder.

func (*FileServer) ServeHTTP

func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error

type MatchFile

type MatchFile struct {
	// The file system implementation to use. By default, the
	// local disk file system will be used.
	FileSystemRaw json.RawMessage `json:"file_system,omitempty" caddy:"namespace=caddy.fs inline_key=backend"`

	// The root directory, used for creating absolute
	// file paths, and required when working with
	// relative paths; if not specified, `{http.vars.root}`
	// will be used, if set; otherwise, the current
	// directory is assumed. Accepts placeholders.
	Root string `json:"root,omitempty"`

	// 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 `/`. To match a regular file, there must
	// be no trailing slash. Accepts placeholders. If
	// the policy is "first_exist", then an error may
	// be triggered as a fallback by configuring "="
	// followed by a status code number,
	// for example "=404".
	TryFiles []string `json:"try_files,omitempty"`

	// How to choose a file in TryFiles. Can be:
	//
	// - first_exist
	// - smallest_size
	// - largest_size
	// - most_recently_modified
	//
	// Default is first_exist.
	TryPolicy string `json:"try_policy,omitempty"`

	// 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 `/remote.php/dav/` using the
	// split value `.php` would try the file `/remote.php`.
	// Each delimiter must appear at the end of a URI path
	// component in order to be used as a split delimiter.
	SplitPath []string `json:"split_path,omitempty"`
	// contains filtered or unexported fields
}

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 by `split_path`.

Even though file matching may depend on the OS path separator, the placeholder values always use /.

func (MatchFile) CELLibrary

func (MatchFile) CELLibrary(ctx caddy.Context) (cel.Library, error)

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']})

func (MatchFile) CaddyModule

func (MatchFile) CaddyModule() caddy.ModuleInfo

CaddyModule returns the Caddy module information.

func (MatchFile) Match

func (m MatchFile) Match(r *http.Request) bool

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) Provision

func (m *MatchFile) Provision(ctx caddy.Context) error

Provision sets up m's defaults.

func (*MatchFile) UnmarshalCaddyfile

func (m *MatchFile) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

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 (MatchFile) Validate

func (m MatchFile) Validate() error

Validate ensures m has a valid configuration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL