Plug.Static
A plug for serving static assets.
It requires two options on initialization:
:at
- the request path to reach for static assets. It must be a string.:from
- the filesystem path to read static assets from. It must be a string, containing a file system path, an atom representing the application name, where assets will be served from the priv/static, or a tuple containing the application name and directory to serve them besides priv/static.
The preferred form is to use :from
with an atom or tuple,
since it will make your application independent from the
starting directory.
If a static asset cannot be found, Plug.Static
simply forwards
the connection to the rest of the pipeline.
Cache mechanisms
Plug.Static
uses etags for HTTP caching. This means browsers/clients
should cache assets on the first request and validate the cache on
following requests, not downloading the static asset once again if it
has not changed. The cache-control for etags is specified by the
cache_control_for_etags
option and defaults to “public”.
However, Plug.Static
also support direct cache control by using
versioned query strings. If the request query string starts with
“?vsn=”, Plug.Static
assumes the application is versioning assets
and does not set the ETag
header, meaning the cache behaviour will
be specified solely by the cache_control_for_vsn_requests
config,
which defaults to “public, max-age=31536000”.
Options
:gzip
- given a request forFILE
, servesFILE.gz
if it exists in the static directory and if theaccept-encoding
header is set to allow gzipped content (defaults tofalse
).:cache_control_for_etags
- sets cache header for requests that use etags. Defaults to"public"
.:cache_control_for_vsn_requests
- sets cache header for requests starting with “?vsn=” in the query string. Defaults to"public, max-age=31536000"
.:only
- filters which paths to lookup. This is useful to avoid file system traversals on every request when this plug is mounted at"/"
. Defaults tonil
(no filtering).
Examples
This plug can be mounted in a Plug.Builder
pipeline as follow:
defmodule MyPlug do
use Plug.Builder
plug Plug.Static, at: "/public", from: :my_app
plug :not_found
def not_found(conn, _) do
send_resp(conn, 404, "not found")
end
end
Summary↑
call(conn, arg2) | Callback implementation for |
init(opts) | Callback implementation for |
Functions
Callback implementation for Plug.call/2
.
Callback implementation for Plug.init/1
.