# Hotlink protection

URL: https://scalws.com/docs/guide/hotlink-protection/
Source: `docs/guide/hotlink-protection.md` in the ScalWS repository

Hotlinking is another site embedding your images (or other files) so that your server
pays for its traffic. ScalWS refuses such requests by their `Referer` header with a route
`referer`, as nginx `valid_referers` does. The route's path chooses which files are
protected; a regex route for image extensions is the usual choice. The design record is
[ADR-0054](https://scalws.com/docs/adr/0054-edge-features-for-scalpanel/).

The `Referer` header is chosen by the client. A browser sends it honestly, but any other
client (curl, a script, a server-side fetch) sends any value or none, and with
`allow_empty: true` a page with `Referrer-Policy: no-referrer` embeds the files freely.
Hotlink protection stops casual embedding by other websites, as nginx `valid_referers`
does; it is not access control.

```yaml
tenants:
  - name: shop
    applications:
      - name: web
        domains: [example.com, www.example.com]
        root: /srv/shop
        route_order: nginx
        runtime: {type: static}
        routes:
          - path: "(?i)^/.*\\.(jpg|png|gif)$"
            path_type: regex
            referer:
              allow_empty: true
              allow_own: true
              hosts: [cdn.example.net, "*.partner.example"]
            runtime: {type: static}
          - path: /
            runtime: {type: static}
```

## Route order

With the default route order (exact, prefix, regex) the prefix route `/` takes every
request and a regex route after it is never used (a warning at load). Set
[`route_order: nginx`](https://scalws.com/docs/guide/configuration/#route-matching) on the application, so regex
routes are tried before prefix routes, as nginx does. Then:

* Put the hotlink route before any broader regex route: regex routes are tried in the
  order they are written, and the first that matches wins.
* The regex sees the client's path as it arrived (decoded and normalised, after
  `.htaccess`), not a path that another route's rewrite produced. For a preview under
  `/sp-ab12/`, match `^/sp-ab12(/.*\.(?:jpg|png|gif))$` and use `rewrite: {path: "$1"}` to
  strip the prefix.
* A regex route is case-sensitive unless the pattern starts with `(?i)`, and it is
  anchored at the start of the path (a leading `^` changes nothing).

## `referer`

| Field | Default | Meaning |
|---|---|---|
| `allow_empty` | `false` | Admit requests without `Referer`, and with one that is not an `http://` or `https://` URL (also an empty value, or more than one header). nginx `none blocked`. |
| `allow_own` | `false` | Admit referers naming the request's host or one of the application's [domains](https://scalws.com/docs/guide/domains/) (`*.x` and `**.x` too; the catch-all `*` adds nothing). nginx `server_names`. |
| `hosts` | `[]` | Allowed referer hosts: a DNS name, an IP literal (`[2001:db8::1]` for IPv6) or `*.suffix` (subdomains only, not `suffix` itself). At most 1024. |
| `status` | `403` | Status of a refusal, 400 to 499. |

How a request's `Referer` is read:

1. No `Referer` header, or a value that is not an `http(s)://` URL, or two headers: allowed
   only with `allow_empty`.
2. Otherwise the host runs from after `://` to the first `/`, `?`, `#` or the end. The port
   is ignored, a trailing dot removed, upper case folded.
3. A host that is not a DNS name, an IPv4 literal or a bracketed IPv6 literal (userinfo
   with `@`, `\`, `%`, spaces, non-ASCII bytes, a bad port, a value over 4096 bytes) is
   refused, as nginx refuses it.
4. The host is allowed when it equals an entry of `hosts`, is below a `*.suffix` entry, or,
   with `allow_own`, equals the request's host or matches one of the application's domains.

Host names are compared case-insensitively. The configuration keeps the `hosts` entries
as you wrote them (a stored generation shows your spelling); they are folded when the
configuration is built. An entry with a path, a port, `~regex`, `host.*` or a `*` other
than a leading `*.` is an error that names the entry.

## The refusal

* A refused request gets `status` with a short text body and `Cache-Control: no-store`.
  The route's `response_headers` apply to this answer too, so a `Cache-Control` they set
  replaces `no-store`.
* No `Vary: Referer` is sent. Routes with `referer` never use ScalWS's own response
  cache, and a refusal is not stored by a cache in front (`no-store`).
* An allowed answer carries neither `no-store` nor `Vary: Referer`. A CDN or shared cache
  in front may store it and then serve it to any referer, so protection at ScalWS is lost
  for that file. Behind such a cache, keep the protected paths uncached there (or protect
  them at the CDN), or add `Vary: Referer` to the route's answers:

  ```yaml
  routes:
    - path: "(?i)^/.*\\.(jpg|png|gif)$"
      path_type: regex
      referer: {allow_empty: true, allow_own: true}
      response_headers: {add: {Vary: Referer}}
      runtime: {type: static}
  ```

  Use `add`, not `set`: `add` keeps the `Vary` values ScalWS sets itself
  (`Accept-Encoding`, `Origin`). Many CDNs treat `Vary: Referer` as uncacheable, which
  has the same effect.
* It is counted in `scalws_security_blocked_total` with `reason="referer"`.
* The check runs after the route's address lists (`allow`, `deny`, network sets) and before
  CORS, basic authentication and the runtime. When `.htaccess` changed the path, the
  `referer` of the client's own route is checked too.

## See also

* [Network sets](https://scalws.com/docs/guide/network-sets/): refuse clients by network or country.
* [ScalPanel edge](https://scalws.com/docs/guide/scalpanel-edge/): the generator's hotlink routes.
* [configuration.md](https://scalws.com/docs/guide/configuration/#route-matching): route matching and route policies.
