
# Behind a reverse proxy

Set `server.forward-headers-strategy=native` (or `framework`), and the application sees each request as the client sent it, not as the proxy passed it: the scheme, the host, the port and the client's address.

## Why

A proxy in front of the server (nginx, Traefik, Caddy, a cloud load balancer) usually ends TLS and passes plain HTTP to the application. Without help, the application sees:

- every request as `http://`, so the session cookie misses `Secure`, and the URIs it builds (redirects, `Location` headers, OAuth2 redirect URIs) start with `http://`;
- the proxy's host and port, not the public ones;
- the proxy's address as the client's address, in logs and in rules that look at the address.

The proxy tells the truth in headers: `Forwarded` (RFC 7239) or `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Port` and `X-Forwarded-For`. But anyone can send these headers. So the server believes them only from the proxies you trust.

## Example

```yaml
# lib/resources/application.yml
server:
  port: 8080
  address: 127.0.0.1               # only the proxy on this host can connect
  forward-headers-strategy: native
  forward-headers:
    trusted-proxies:
      - 127.0.0.1
      - ::1
```

```properties
server.port=8080
server.address=127.0.0.1
server.forward-headers-strategy=native
server.forward-headers.trusted-proxies=127.0.0.1,::1
```

The nginx side. Each `proxy_set_header` replaces what the client sent:

```nginx
server {
  listen 443 ssl;
  server_name shop.example.com;
  # ssl_certificate ... ;

  location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host              $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host  $host;
    proxy_set_header X-Forwarded-Port  $server_port;
    proxy_set_header X-Forwarded-For   $remote_addr;
  }
}
```

In a controller, the request now shows the public view:

```dart
@GetMapping('/whoami')
Map<String, Object?> whoami(ServerHttpRequest request) => {
  'uri': '${request.uri}',            // https://shop.example.com/whoami
  'secure': request.isSecure,         // true
  'client': request.remoteAddress,    // the browser's address, not 127.0.0.1
};
```

## Properties

| Key | Type | Default | Meaning |
|---|---|---|---|
| `server.forward-headers-strategy` | `none` / `native` / `framework` | `none` | Whether the forwarded headers are applied. |
| `server.forward-headers.trusted-proxies` | `List<String>` | loopback and private networks | Whose forwarded headers are believed: addresses and CIDR ranges. |

### `server.forward-headers-strategy`

- **Type:** enum. **Default:** `none`.

| Value | What happens |
|---|---|
| `none` | The headers are not read. The request is what reached the server. No filter is added; the headers stay in the request as they came. |
| `native` | The `forwardedHeaderFilter` bean is added: the headers of trusted proxies are applied. In Spring Boot: the server's own support (Tomcat's `RemoteIpValve`). |
| `framework` | Exactly the same as `native` here. In Spring Boot: Spring's `ForwardedHeaderFilter`. |

- **Why change it:** the application runs behind a proxy that ends TLS or changes the host.
- **Example:** `server.forward-headers-strategy=native`.
- **Wrong value:** `server.forward-headers-strategy=always` stops the start with a binding failure that names the key.
- **Do not set it** when clients reach the server directly and no proxy sets the headers. With the default trusted list, a client on your private network could then claim another address or HTTPS.

### `server.forward-headers.trusted-proxies`

- **Type:** a list of IP addresses and CIDR ranges, as a comma list or a YAML list. IPv4 and IPv6. **Default:** not set, which means Tomcat's `internalProxies`:

```text
127.0.0.0/8     10.0.0.0/8      172.16.0.0/12   192.168.0.0/16
169.254.0.0/16  100.64.0.0/10   ::1/128         fc00::/7        fe80::/10
```

That is loopback, the private networks, link-local addresses and shared (CGNAT) addresses.

- **What it does:** the forwarded headers are applied only when the direct peer (the address the TCP connection comes from) is in this list. It is also used to find the client in `X-Forwarded-For` (below).
- **Setting it replaces the default list.** It does not add to it. Include loopback yourself if your proxy runs on the same host.
- **A single address** is a range of one: `192.168.1.10` is `192.168.1.10/32`.
- **IPv4 inside IPv6** (`::ffff:10.1.2.3`) matches the IPv4 ranges.
- **Why change it:** narrow it to the real proxies (the default trusts every machine of every private network); or add the addresses of a load balancer that is not on a private network.
- **Example:** `server.forward-headers.trusted-proxies=10.0.12.0/24,10.0.13.7`.
- **Wrong value:** an entry that is not an address or a range stops the start, for example `Not an address or range: 10.0.0.0/99`.
- **Only with a strategy.** With `server.forward-headers-strategy=none` the list is not read.
- **Not in Spring Boot.** Spring Boot sets Tomcat's list with `server.tomcat.remoteip.internal-proxies`, a regular expression.

## How the headers are read

The `forwardedHeaderFilter` runs first of all filters (order `-10000`; the session filter is at `-1000`, the security chain at `-100`). For each request:

1. **No forwarded header:** the request passes as it is.
2. **The peer is not trusted:** the headers are ignored. Debug log: `Forwarded headers from 203.0.113.99 ignored: not a trusted proxy (server.forward-headers.trusted-proxies)`.
3. **The peer is trusted:** the headers are applied, then removed from the request for the rest of the chain. Debug log: `Forwarded headers applied: https://shop.example.com`. Header values are never logged.

Which headers:

- **`Forwarded`**, when present, is used alone; the `X-Forwarded-*` headers are then ignored. The first element gives `proto` and `host` (with its port: `host=shop.example.com:8443`). Every element's `for` makes the address chain. Quoted values (`for="[2001:db8::7]:4711"`) are understood.
- **Otherwise** `X-Forwarded-Proto`, `X-Forwarded-Host` and `X-Forwarded-Port` (the first value of each comma list), and `X-Forwarded-For` (every value, of every such header).

What changes:

| Request member | From |
|---|---|
| `uri` scheme | `proto` / `X-Forwarded-Proto`: only `http` or `https`. A new scheme without a host or port takes its own default port (443, 80). |
| `uri` host and port | `host` / `X-Forwarded-Host` (`host`, `host:port`, `[v6]`, `[v6]:port`), then `X-Forwarded-Port` (1 to 65535). |
| `isSecure` | `true` when the scheme is `https` (or `wss`). |
| `remoteAddress` | the client, from the address chain (below). |

The path and the query never change.

**The client's address.** The chain is read from the right: the rightmost entry was added by the proxy nearest to the server. Each trusted proxy is skipped. The first address that is not a trusted proxy is the client. So with `X-Forwarded-For: 6.6.6.6, 198.51.100.4, 10.0.0.9`, the client is `198.51.100.4`: the `6.6.6.6` on the left was written by the client itself and is not believed. An entry that is no address (`unknown`, an obfuscated name) stops the walk at the last address found.

**Invalid values are ignored**, one by one: a scheme other than `http` and `https`, a host with a path, a space or a line break, a port out of range, a broken IPv6 literal. The rest still applies.

## What it affects

- The session cookie gets `Secure` behind a TLS proxy (when `server.session.cookie.secure` is not set). See [Sessions](../sessions.md).
- URIs built from `request.uri` use the public scheme and host: the redirect URI of the security starter's OAuth2 login, the URL saved before a login, and any URI your code builds from the request.
- CORS and WebSocket origin checks compare the `Origin` with the public origin.
- Logs and rules that read `remoteAddress` see the client.

## Security

- **The proxy must replace the headers**, not add to what the client sent. nginx's `proxy_set_header` replaces. Traefik and cloud load balancers set them. With `$proxy_add_x_forwarded_for`, nginx appends; this is safe for the client's address (it is read from the right), but `X-Forwarded-Proto` and `X-Forwarded-Host` must still be set, not passed through.
- **Keep the list small.** Each trusted address can make the application believe anything. Never put `0.0.0.0/0` or `::/0` in it.
- **Make the proxy the only way in.** Listen on `127.0.0.1` when the proxy runs on the same host, or block the application's port with a firewall. Otherwise a client on a private network could connect directly and be trusted by the default list.
- **`dart:io` limits.** The server reads a raw `\` in the path as `/`, and refuses a request with both `Content-Length` and `Transfer-Encoding` only in the spellings where it sees both headers. Use a proxy that refuses such requests. See [The embedded server](index.md).

## Rules and edge cases

- **`X-Forwarded-Prefix` is not read.** When the proxy serves the application under a prefix, let it pass the full path and set `server.context-path` to the prefix.
- **`X-Forwarded-Ssl` and `Front-End-Https` are not read.** Use `X-Forwarded-Proto` or `Forwarded`.
- **Several instances.** Sessions live in the memory of one process. Route each client to the same instance (a sticky cookie). The cookies the security starter keeps before a login are signed: give every instance the same `spring.security.cookie.secret`.
- **With TLS on the server too** (`server.ssl.*`), the scheme is `https` already. The headers can still change the host and the client's address.

## In Spring (Java)

```properties
server.forward-headers-strategy=native
server.tomcat.remoteip.internal-proxies=10\\.0\\.12\\.\\d{1,3}
```

Differences that matter:

- `native` and `framework` do the same thing here: they apply the headers of trusted proxies only, as Tomcat's `RemoteIpValve` does. Spring's `ForwardedHeaderFilter` (`framework`) believes every peer.
- The trusted proxies are a list of addresses and CIDR ranges (`server.forward-headers.trusted-proxies`), not Tomcat's regular expression (`server.tomcat.remoteip.internal-proxies`).
- `X-Forwarded-Prefix` and `X-Forwarded-Ssl` are not read.
- An unknown strategy stops the start.

## See also

- [The embedded server](index.md)
- [TLS (HTTPS)](ssl.md)
- [Sessions](../sessions.md)
- [Filters](../filters.md)
- [CORS](../cors.md)
- [All properties](../properties.md)
