diff --git a/src/v3/configuration/file.md b/src/v3/configuration/file.md index 718c218..1f78727 100644 --- a/src/v3/configuration/file.md +++ b/src/v3/configuration/file.md @@ -206,8 +206,6 @@ maintenance-mode-status = 503 # [[advanced.rewrites]] # source = "**/*.{png,ico,gif}" # destination = "/assets/favicon.ico" -## Optional redirection -# redirect = 301 # [[advanced.rewrites]] # source = "**/*.{jpg,jpeg}" diff --git a/src/v3/features/custom-http-headers.md b/src/v3/features/custom-http-headers.md index d79df35..abcab8d 100644 --- a/src/v3/features/custom-http-headers.md +++ b/src/v3/features/custom-http-headers.md @@ -29,11 +29,15 @@ A particular set of HTTP headers can only be applied when a `source` matches aga ### Source -The source is a [Glob pattern]() that should match against the URI that is requesting a resource file. +The source is a [Glob pattern]() that should match against the URI that is requesting a resource file. Unlike in [URL redirects](url-redirects.md), `*` also matches `/` here. + +An entry applies when its source matches the request path or the path of the file that answers the request. So `/dir/` gets the headers of `/dir/index.html` as well as those of `/dir/`, `/page` those of `/page.html`, and a [negotiated markdown](markdown-content-negotiation.md) variant those of its `.md` file. The `308` that adds a [trailing slash](trailing-slash-redirect.md) serves no file. + +Both paths are matched as SWS serves them, decoded and without empty or `.` segments, so `//a/./b` and `/a%2Fb` get the headers of `source = "/a/b"`. See [path matching](url-redirects.md#path-matching) for how to write spaces, non-ASCII and glob characters in a source. ### Headers -A set of valid plain [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) to be applied. +A set of valid plain [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) to be applied. An array sends the header once per value, for example `Link = ["; rel=preload", "; rel=preload"]`. ### Status @@ -52,9 +56,9 @@ SWS validates the codes at startup and fails to start on an empty array or a cod An optional string that selects which responses the entry applies to: - `files` (default): responses of the static file handler only, including error responses such as `404 Not Found` and plain [URL rewrites](url-rewrites.md), which are served as files. -- `all`: also the responses SWS returns before serving a file: [URL redirects](url-redirects.md), [URL rewrites](url-rewrites.md) with `redirect`, the [health endpoints](health-endpoint.md), the [metrics endpoint](metrics.md), CORS requests rejected with `403 Forbidden`, [Basic Authentication](basic-authentication.md) challenges, [maintenance mode](maintenance-mode.md) and `405 Method Not Allowed`. +- `all`: also the responses SWS returns before serving a file: [URL redirects](url-redirects.md), the [health endpoints](health-endpoint.md), the [metrics endpoint](metrics.md), CORS requests rejected with `403 Forbidden`, [Basic Authentication](basic-authentication.md) challenges, [maintenance mode](maintenance-mode.md) and `405 Method Not Allowed`. -These early responses serve no file, so `source` is matched against the request path as is. `scope` can be combined with `status`. +These early responses serve no file, so `source` is matched against the request path only. `scope` can be combined with `status`. > [!WARNING] Broad patterns > diff --git a/src/v3/features/trailing-slash-redirect.md b/src/v3/features/trailing-slash-redirect.md index cd86c3c..145c29f 100644 --- a/src/v3/features/trailing-slash-redirect.md +++ b/src/v3/features/trailing-slash-redirect.md @@ -10,3 +10,7 @@ static-web-server \ --root ./my-public-dir \ --redirect-trailing-slash true ``` + +When enabled, a request for a directory without a trailing slash, such as `/docs`, gets a `308 Permanent Redirect` to `/docs/`. This also applies to requests [rewritten](url-rewrites.md#trailing-slash-redirect) to a directory. + +A regular file requested with a trailing slash, such as `/app.js/`, answers `404 Not Found`. diff --git a/src/v3/features/url-redirects.md b/src/v3/features/url-redirects.md index c04564c..f9c79ad 100644 --- a/src/v3/features/url-redirects.md +++ b/src/v3/features/url-redirects.md @@ -23,14 +23,27 @@ Each table entry should have the following key/value pairs: > > The incoming request(s) will reach the `destination` only if the request(s) URI matches the `source` pattern. +Rules apply in order and the first match wins. Redirects run before [URL rewrites](url-rewrites.md). + ### Host Optional `host` redirect entry to be matched against the incoming host URI. If a `host` redirect setting is specified then SWS will attempt to match the value against the incoming URI host (request), applying the required redirect entry or ignoring it otherwise. +- The value is a host name, an IPv4 address or a bracketed IPv6 address (`[::1]`), with an optional port. +- Letter case is ignored and IPv6 addresses are compared by value. +- Without a port, the entry matches any port. With a port, such as `example.com:8080`, it matches only requests carrying that port. A default port is not implied: `example.com:80` never matches `Host: example.com`. +- The host is taken from the request URI (absolute-form requests, HTTP/2) or else from the `Host` header. + +SWS fails to start on an invalid `host`, including wildcards such as `*.example.com`. + > [!TIP] www to non-www redirects > > The host entry allows for instance to perform www to non-www redirects or vice versa (see example below). +> [!WARNING] The client chooses the host +> +> A host-bound rule only applies to requests sent with that host. The same path requested with another host skips it, so don't rely on such a rule to protect content served for several hosts. + ### Source The source is a [Glob pattern]() that should match against the URI that is requesting a resource file. @@ -48,16 +61,40 @@ The glob pattern functionality is powered by the [globset](https://docs.rs/globs > > In later versions, the default has changed such that `*` does not match the path separator. +#### Path matching + +Sources match the request path as SWS serves it: decoded, without empty or `.` segments. So `//a/./b`, `/a%2Fb` and `/%61/b` all match `source = "/a/b"`. The query string is not part of the path. On macOS and Windows, ASCII letter case is ignored, as their file systems do. + +Write a source as the path is served: + +- A source that starts with neither `/` nor a glob character, or holds `//`, a `.` or `..` segment or an escaped `/` (`%2F`), matches no request. SWS logs a warning at startup. +- A space, a non-ASCII character or a percent-escape in either hex case can be written as is: `/my files/*`, `/café/*` and `/caf%C3%A9/*` are the same source. +- To match a glob character such as `[`, `{` or `?` literally, quote it with a backslash (`/a\[b`) or as the only member of a class (`/a[[]b`). On Windows, `\` separates path segments, so use the class. +- `?` and a class such as `[a-z]` match one character of the percent-encoded path, so never a space or another character the path holds encoded. SWS fails to start on a class that holds such a character among other members, in a range or negated (`/[a b]x`), and suggests an alternation instead (`{a,%20}`). + +Some URLs serve the same content and are still separate paths, each needing its own rule: a directory and its index file (`/dir/` and `/dir/index.html`), a path and its `.html` file (`/page` and `/page.html`), and a file and its pre-compressed `.gz`, `.br` or `.zst` variant requested by name. + +When rules are configured, a request path longer than 8 KiB answers `414 URI Too Long`. + ### Destination The value can be either a local file path that maps to an existing file on the system or an external URL. It could look like `/some/directory/file.html`. It is worth noting that the `/` at the beginning indicates the server's root directory. +The request query string is appended to the destination, after the destination's own query and before its fragment. For example, `destination = "/new?from=old"` redirects `/old?page=2` to `/new?from=old&page=2`. + +SWS fails to start when a destination holds a character that a URI only holds percent-encoded, such as a space, `"`, `<`, `>`, `\`, `|` or a non-ASCII character. Write it percent-encoded instead (`%20` for a space). + #### Replacements Additionally, a `destination` supports replacements for every Glob pattern group that matches against the `source`. The replacement order starts from `0` to `n` and is defined with a dollar sign followed by an index (Glob pattern group occurrence). +- `$0` is the whole path. Every `{a,b}` alternation, `{*}` or `{**}` group and `**/` segment is a group from `$1` on, in source order. In `**/{*}.{jpg,png}`, `$1` is the leading directory, `$2` the file name and `$3` the extension. A trailing `/**` is not a group: use `/{**}` to capture it. +- Captures take the served spelling of the path: `/old/a%2fb` with `destination = "/new/$1"` gives `/new/a/b`. +- Placeholders are only allowed in the path, query or fragment of a destination: `https://$1.example.org/` fails at startup. A destination that starts with a placeholder, such as `/$1`, stays a path on the same host. +- A placeholder in the query is percent-encoded as one value, so its `&`, `=`, `+` and `;` can't add parameters. + > [!TIP] Group your Glob patterns > > When using replacements, also group your Glob pattern by surrounding them with curly braces so every group should map to its corresponding replacement.
@@ -95,8 +132,9 @@ kind = 302 ## Note that we're using curly braces to group the `*` wildcard. ## See https://docs.rs/globset/latest/globset/#syntax source = "**/{*}.{jpg,jpeg,svg}" +## `$1` is the leading directory, `$2` the file name and `$3` the extension. ## For example, the destination will result in `http://localhost/assets/abcdef.jpeg` -destination = "http://localhost/assets/$1.$2" +destination = "http://localhost/assets/$2.$3" kind = 301 # d. Simple route redirect using the `host` option @@ -111,18 +149,17 @@ kind = 301 If you request something like: ```sh -curl -I http://localhost:4433/abcdef.jpeg +curl -I http://localhost:8080/abcdef.jpeg ``` -Then the server logs should look something like this: +Then the server logs (`--log-level debug --log-format pretty`) should look something like this: ```log -2023-07-11T21:11:22.217358Z INFO static_web_server::handler: incoming request: method=HEAD uri=/abcdef.jpeg -2023-07-11T21:11:22.217974Z DEBUG static_web_server::handler: url redirects glob pattern: ["$0", "$1", "$2"] -2023-07-11T21:11:22.217992Z DEBUG static_web_server::handler: url redirects regex equivalent: (?-u)^(?:/?|.*/)(?:[^/]*)\.(?:svg|jpeg|jpg)$ -2023-07-11T21:11:22.218002Z DEBUG static_web_server::handler: url redirects glob pattern captures: ["abcdef.jpeg", "abcdef", "jpeg"] -2023-07-11T21:11:22.218076Z DEBUG static_web_server::handler: url redirects glob pattern destination: "http://localhost/assets/$1.$2" -2023-07-11T21:11:22.218712Z DEBUG static_web_server::handler: url redirects glob pattern destination replaced: "http://localhost/assets/abcdef.jpeg" -2023-07-11T21:11:22.218739Z TRACE static_web_server::handler: uri matches redirects glob pattern, redirecting with status '301 Moved Permanently' -... +2026-11-28T21:47:33.778285+01:00 DEBUG static_web_server::url_rules::destination: url rule regex equivalent: (?i)^(/?|.*/)([^/]*)\.(jpg|jpeg|svg)$ +2026-11-28T21:47:33.778339+01:00 DEBUG static_web_server::url_rules::destination: url rule glob pattern captures: ["/abcdef.jpeg", "/", "abcdef", "jpeg"] +2026-11-28T21:47:33.778355+01:00 DEBUG static_web_server::url_rules::destination: url rule glob pattern destination: "http://localhost/assets/$2.$3" +2026-11-28T21:47:33.778379+01:00 DEBUG static_web_server::url_rules::destination: url rule glob pattern destination replaced: "http://localhost/assets/abcdef.jpeg" +2026-11-28T21:47:33.778414+01:00 INFO static_web_server::log_addr: response method="HEAD" uri="/abcdef.jpeg" status=301 ``` + +The `(?i)` prefix appears on macOS and Windows only, where letter case is ignored. diff --git a/src/v3/features/url-rewrites.md b/src/v3/features/url-rewrites.md index 540c20e..ae1bed3 100644 --- a/src/v3/features/url-rewrites.md +++ b/src/v3/features/url-rewrites.md @@ -12,22 +12,34 @@ URI rewrites are particularly useful with pattern matching ([globs]( [!INFO] Note > > The incoming request(s) will reach the `destination` only if the request(s) URI matches the `source` pattern. +Rules apply in order and the first match wins. A rewritten request is not matched against the rules again. [URL redirects](url-redirects.md) run before rewrites. + +> [!WARNING] `redirect` was removed +> +> SWS fails to start on a rewrite with the `redirect` key. Move such a rule to [`[[advanced.redirects]]`](url-redirects.md) and set its status code with `kind`. + +### Host + +An optional host name the request must be addressed to. It is matched as the [`host` of URL redirects](url-redirects.md#host): ignoring letter case, comparing IPv6 addresses by value, and any port unless it names one. + ### Source It's a [Glob pattern]() that should match against the URI that is requesting a resource file. The glob pattern functionality is powered by the [globset](https://docs.rs/globset/latest/globset/) crate which supports Standard Unix-style glob syntax. +Sources match the request path as SWS serves it, decoded and without empty or `.` segments. See [path matching](url-redirects.md#path-matching) for how to write spaces, non-ASCII and glob characters in a source. + > [!TIP] Glob pattern syntax > > For more details about the Glob pattern syntax check out the [globset documentation](https://docs.rs/globset/latest/globset/#syntax). @@ -41,13 +53,15 @@ The glob pattern functionality is powered by the [globset](https://docs.rs/globs ### Destination -The value should be a relative or absolute URL. A relative URL could look like `/some/directory/file.html`. An absolute URL can be `https://external.example.com/` for example. +The value should be a path starting with `/`, such as `/some/directory/file.html`, or an absolute URL, such as `http://internal.local/file.html`. SWS fails to start on any other value, on a destination with a fragment (`#`), and on characters a URI only holds percent-encoded. + +The request query string is appended after the destination's own query, as for [URL redirects](url-redirects.md#destination). A destination that grows longer than a URI can be answers `414 URI Too Long`. #### Replacements Additionally, a `destination` supports replacements for every Glob pattern group that matches against the `source`. -Replacements order start from `0` to `n` and are defined with a dollar sign followed by an index (Glob pattern group occurrence). +Replacements order start from `0` to `n` and are defined with a dollar sign followed by an index (Glob pattern group occurrence). Groups are numbered as for [URL redirects](url-redirects.md#replacements): in `**/{*}.{png,gif}`, `$1` is the leading directory, `$2` the file name and `$3` the extension. > [!TIP] Group your Glob patterns > @@ -56,9 +70,13 @@ Replacements order start from `0` to `n` and are defined with a dollar sign foll #### Destination processing -How destination is processed depends on whether the `redirect` key (see below) is present. If it is present, SWS will perform an _external_ redirect. It will send a redirect response to the client, and the browser will usually proceed to the destination. In case of a relative URL, it will be another page on the same server. An absolute URL can result in navigation to another server. +SWS performs an _internal_ redirect. It will attempt to retrieve the file denoted by the destination and send it to the client. While it is possible to specify an absolute URL here as well, it will always be processed by the same SWS instance. It will result by the request being mapped to a different [virtual host](virtual-hosting.md) however if a matching virtual host is present. -Without a `redirect` key, SWS will perform an _internal_ redirect. It will attempt to retrieve the file denoted by the destination and send it to the client. While it is possible to specify an absolute URL here as well, it will always be processed by the same SWS instance. It will result by the request being mapped to a different [virtual host](virtual-hosting.md) however if a matching virtual host is present. +To send a redirect response to the client instead, use [URL redirects](url-redirects.md). + +#### Trailing slash redirect + +With [trailing slash redirect](trailing-slash-redirect.md) enabled, a request rewritten to a directory without a trailing slash gets a `308 Permanent Redirect`. The `Location` is the client's path with a `/` appended when that path rewrites to the same directory, so the rewrite destination stays hidden. Otherwise it is the rewritten path. #### Different roots within the same virtual host @@ -81,18 +99,7 @@ root = "/usr/srv/alternative-root" A request to `/index.html` will be mapped to `/usr/srv/www/index.html`, yet `/test/hi.txt` will be mapped to the file `/usr/srv/alternative-root/test/hi.txt`. -This approach has two caveats: - -1. When SWS produces redirects (e.g. redirecting `http://internal.local/test/subdir` to `http://internal.local/test/subdir/`), it isn't aware of rewrites. Unless the path part of the URL is identical before and after rewrite (like in the example above), this will result in broken redirects. -2. While the `internal.local` virtual host isn't normally accessed directly, this doesn't mean that it isn't possible for someone knowing (or guessing) its name. You should consider all files under the virtual host's root as public. Don't put any secrets in it even if these aren't accessible via rewrites. - -### Redirect - -An optional number that indicates the HTTP response code (redirect). -The values can be: - -- `301` for "Moved Permanently" -- `302` for "Found" (Temporary Redirect) +While the `internal.local` virtual host isn't normally accessed directly, this doesn't mean that it isn't possible for someone knowing (or guessing) its name. You should consider all files under the virtual host's root as public. Don't put any secrets in it even if these aren't accessible via rewrites. ## Examples @@ -106,12 +113,11 @@ The values can be: source = "**/*.{png,ico,gif}" destination = "/assets/generic1.png" -# b. Route rewrite example with redirection +# b. Route rewrite example for a single host [[advanced.rewrites]] -source = "**/*.{jpg,jpeg}" -destination = "/images/generic2.png" -## NOTE: `redirect` can be omitted too -redirect = 301 +host = "docs.example.com" +source = "/{**}" +destination = "/docs/$1" # c. Route rewrite example with destination replacements [[advanced.rewrites]] @@ -119,24 +125,23 @@ redirect = 301 ## See https://docs.rs/globset/latest/globset/#syntax source = "**/{*}.{png,gif}" ## For example, the destination will result in `/assets/abcdef.png` -destination = "/assets/$1.$2" +destination = "/assets/$2.$3" ``` If you request something like: ```sh -curl -I http://localhost/abcdef.png +curl -I http://localhost:8080/abcdef.png ``` -Then the server logs should look something like this: +Then the server logs (`--log-level debug --log-format pretty`) should look something like this: ```log -2023-07-08T20:31:36.606035Z INFO static_web_server::handler: incoming request: method=HEAD uri=/abcdef.png -2023-07-08T20:31:36.608439Z DEBUG static_web_server::handler: url rewrites glob patterns: ["$0", "$1", "$2"] -2023-07-08T20:31:36.608491Z DEBUG static_web_server::handler: url rewrites regex equivalent: (?-u)^(?:/?|.*/)(?:[^/]*)\.(?:gif|png)$ -2023-07-08T20:31:36.608525Z DEBUG static_web_server::handler: url rewrites glob pattern captures: ["abcdef.png", "abcdef", "png"] -2023-07-08T20:31:36.608561Z DEBUG static_web_server::handler: url rewrites glob pattern destination: "/assets/$1.$2" -2023-07-08T20:31:36.609655Z DEBUG static_web_server::handler: url rewrites glob patterns destination replaced: "/assets/abcdef.png" -2023-07-08T20:31:36.609735Z TRACE static_web_server::static_files: dir: base="public", route="assets/abcdef.png" -... +2026-11-28T21:47:33.749823+01:00 DEBUG static_web_server::url_rules::destination: url rule regex equivalent: (?i)^(/?|.*/)([^/]*)\.(png|gif)$ +2026-11-28T21:47:33.749978+01:00 DEBUG static_web_server::url_rules::destination: url rule glob pattern captures: ["/abcdef.png", "/", "abcdef", "png"] +2026-11-28T21:47:33.750025+01:00 DEBUG static_web_server::url_rules::destination: url rule glob pattern destination: "/assets/$2.$3" +2026-11-28T21:47:33.750085+01:00 DEBUG static_web_server::url_rules::destination: url rule glob pattern destination replaced: "/assets/abcdef.png" +2026-11-28T21:47:33.752204+01:00 INFO static_web_server::log_addr: response method="HEAD" uri="/abcdef.png" status=200 ``` + +The `(?i)` prefix appears on macOS and Windows only, where letter case is ignored. diff --git a/src/v3/features/virtual-hosting.md b/src/v3/features/virtual-hosting.md index bd7cd94..f96f533 100644 --- a/src/v3/features/virtual-hosting.md +++ b/src/v3/features/virtual-hosting.md @@ -14,6 +14,8 @@ Virtual hosting can be useful for serving more than one static website from the By default, SWS will always serve files from the main `root` directory. If you configure virtual hosting and the "Host" header matches, SWS will instead look for files in an alternate root directory you specify. +The `host` is matched as the [`host` of URL redirects](url-redirects.md#host): letter case is ignored, IPv6 addresses are compared by value, and a `host` without a port matches any port, while `sales.example.com:8080` matches only that port. SWS fails to start on an invalid `host`, including wildcards. + ## Examples ```toml diff --git a/src/v3/migration-guide.md b/src/v3/migration-guide.md index 7ece9b5..80abdc9 100644 --- a/src/v3/migration-guide.md +++ b/src/v3/migration-guide.md @@ -175,6 +175,30 @@ v3 binds the default `--host ::` as a dual-stack socket, so it accepts IPv4 too **Action:** If another service listens on `0.0.0.0` at the same port, SWS now fails with "address in use": change one of the ports, or add `--ipv6-only` to keep `::` IPv6-only as in v2. See [IPv6-Only Host](./features/ipv6-only.md). +### 17. URL rewrites no longer redirect + +v3 removes the `redirect` key of `[[advanced.rewrites]]` and fails to start when a rule sets it. + +**Action:** Move such rules to `[[advanced.redirects]]` and set `kind` to `301` or `302`. See [URL Redirects](./features/url-redirects.md). + +### 18. Stricter rule sources and destinations + +Redirect, rewrite and custom header sources match the request path as it is served: decoded, without empty or `.` segments. SWS also validates rules at startup instead of answering `500` per request. See [path matching](./features/url-redirects.md#path-matching). + +- Invalid or wildcard `host` values, destinations with characters a URI only holds percent-encoded (such as a space or `|`), and placeholders before the destination path (`https://$1.example.org/`) fail at startup. +- Rewrite destinations must be a `/` path or an absolute URI, without `#`. +- Character classes that hold a space or another character paths spell encoded among other members (`[a b]`) fail at startup. +- Sources written with `//`, a `.` segment or a needless escape no longer match. +- A rule `host` with a port matches only that port, and a request path over 8 KiB answers `414` when rules are configured. + +**Action:** Fix the rules SWS reports at startup, percent-encode destinations, and write sources as the served path. + +### 19. A file requested as a directory answers `404` + +Earlier versions served `app.js` for `/app.js/`. v3 answers `404 Not Found`. + +**Action:** Usually none. Fix links that add a trailing slash to a file. + ## Quick migration checklist 1. **Port & root:** Add `--port 80` and `--root ./public` if you were relying on the defaults. @@ -193,3 +217,6 @@ v3 binds the default `--host ::` as a dual-stack socket, so it accepts IPv4 too 14. **Cache-Control:** No action needed. HTML now gets `no-cache`. 15. **Fallback page:** No action needed. Missing assets keep their `404`. 16. **Dual-stack:** Make sure no other service uses the same port on `0.0.0.0`, or add `--ipv6-only`. +17. **Rewrites:** Move rewrites with `redirect` to `[[advanced.redirects]]` with `kind`. +18. **URL rules:** Fix the redirect, rewrite and header rules SWS reports at startup. +19. **Trailing slash on files:** No action needed. `/file/` answers `404`.