This commit is contained in:
Mateusz Gruszczyński committed 2026-11-23 11:07:13 +01:00
1 parent 27b640a0df
commit aa27866531
46 files changed
+3368 -189

No files matched your search

+49 -1
View File
@@ -10,12 +10,60 @@ Custom locations add exceptions to a Vhost's normal source. They are **not** req
| `prefix_priority` | Longest prefix that suppresses regex evaluation | Ahead of regex when matched |
| `regex` / `regex_insensitive` | Case-sensitive or insensitive regular expression | Tested in configured order after priority-prefix rules |
| `prefix` | Ordinary longest matching path prefix | Fallback among matching rules |
| `any` | Every path — a rule for the whole host, selected only by its conditions | Same as regex: configured order, after priority-prefix rules |
Glob wildcards (`*.mp3`) are not supported; use a regular expression such as `\.mp3$`. Regular expressions use the Rust `regex` syntax (no look-around or back-references).
Encoded `/` separators (`%2F` / `%2f`) are normalized to real `/` only for location matching and security policy. Other ambiguous or unsafe encoded path forms remain rejected. In `preserve` rewrite mode the original encoded request target is forwarded unchanged to the upstream, so `/a%2Fb?x=1` is matched as `/a/b` but reaches the backend as `/a%2Fb?x=1`. Rewritten modes generate a new normalized target instead. Avoid overlapping regex rules when order matters; test paths with and without trailing `/`.
## Request conditions (routing by header, cookie, IP…)
A location can require extra **conditions** besides its path — the RustProxy equivalent of HAProxy ACLs in `use_backend <backend> if <acl> <acl>`. Each condition tests one request attribute:
| `source` | `name` | Operators | Notes |
|---|---|---|---|
| `header` | header name | `equals`, `exists`, `prefix`, `suffix`, `contains`, `regex` | Repeated header lines are tested one by one. |
| `cookie` | cookie name | same as header | |
| `query` | parameter name | same as header | Raw (not URL-decoded) value. |
| `method` | — | `equals` | `GET`, `POST`… (case-insensitive). |
| `ip` | — | `cidr` | Client address after trusted forwarding / Cloudflare handling; values are IPs or networks (`10.0.0.0/8`, `2001:db8::/32`). |
| `host` | — | `equals`, `prefix`, `suffix`, `contains`, `regex` | Host name without port, lower-case; useful with wildcard Vhosts. |
| `country` | — | `equals` | ISO codes from the GeoIP database or Cloudflare (`PL`, `DE`). |
Rules: **all conditions of a location must hold (AND)**; a condition matches when **any of its `values`** matches (OR); `negate` inverts one condition; `ignore_case` makes header, cookie and query comparisons case-insensitive. For an OR between whole rules add several locations. Up to 16 conditions per location and 64 values per condition.
Selection with conditions:
1. A location whose conditions fail is **skipped** and the next candidate is tried — so `/api/` with `X-Beta: 1` and a plain `/api/` can coexist, and the request falls through to the plain one without the header.
2. For exact paths and for prefixes of equal length a location with conditions is preferred over one without; regular expressions and `any` rules are tried **in list order** (move rules with **↑ / ↓** in the panel). A conditional regex placed after an identical unconditional one would never match and is rejected.
3. **Rule for the whole host:** match type `any` (panel: *Add rule for the whole host*) applies to every path, like a frontend-level `use_backend … if …`. It needs at least one condition and ranks like a regular expression: exact paths and priority prefixes still win, ordinary prefixes lose.
4. Responses of locations with conditions are **never cached** (their content depends on request attributes outside the cache key), and `cache` must be inherit or off. Unconditional locations and the main source cache as before.
5. Internal (error-fallback) locations cannot have conditions.
Example — beta testers by header, office network with a staff cookie for the whole host, `.mp3` files for EU visitors:
```json
"routes": [
{ "id": "api-beta", "path_prefix": "/api/", "backend_ids": ["beta"],
"conditions": [{ "source": "header", "name": "X-Beta", "values": ["1"] }] },
{ "id": "api", "path_prefix": "/api/" },
{ "id": "office", "match_type": "any", "backend_ids": ["office"],
"conditions": [
{ "source": "ip", "operator": "cidr", "values": ["10.0.0.0/8"] },
{ "source": "cookie", "name": "staff", "operator": "exists" } ] },
{ "id": "mp3-eu", "match_type": "regex_insensitive", "path_prefix": "\\.mp3$",
"backend_ids": ["mp3_eu_1", "mp3_eu_2"], "load_balancing": { "algorithm": "hash" },
"conditions": [{ "source": "country", "values": ["PL", "DE", "FR"] }] }
]
```
### Routing tester
**Vhosts → Edit → Custom locations → Test routing** evaluates the unsaved draft in the browser: enter a method, URL, client IP, country and headers (cookies as a `Cookie:` header) to see which location wins, why every other location was skipped (path ✓/✗ and each condition ✓/✗), the backend or hash target and whether the cache is bypassed. Its matching logic is checked against the proxy with the shared cases in `tests/fixtures/routing_conditions_cases.json` (`tools/dev/test_routing_tester.js`). Regular expressions are run by the browser engine, which covers the common syntax; the server always validates the saved configuration.
## Actions
- **Proxy:** use the Vhost backend pool or target a specific backend. A location can have an explicit cache override.
- **Proxy:** use the Vhost backend pool, a **backend group** (`backend_ids`) or one specific backend. The pool or group can use its own algorithm, hash key and affinity (`load_balancing`), for example a consistent hash of the path for `.mp3` files only — see [Load balancing](LOAD_BALANCING.md#location-backend-groups). A location can have an explicit cache override.
- **Web Server:** reference an existing Web Service with its saved document root and PHP/static settings.
- **Local response:** return a chosen `200–599` status, content type and body without connecting to an origin. `HEAD`, `204` and `304` do not return a body.
- **Redirect:** issue `301`, `302`, `303`, `307` or `308` to a valid absolute HTTP(S) target. Query preservation is configurable. Redirect rewrite expressions may reference regex captures.
+1 -1
View File
@@ -10,7 +10,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
|---|---|
| Vhosts | Exact and wildcard hostnames, aliases, several listeners per Vhost, per-Vhost HTTP/2 and HTTP/3 switches |
| Backends | HTTP and HTTPS origins, HTTP/1.1, automatic ALPN (H2/H1), strict HTTP/2 and H2C, optional upstream certificate verification with custom CA and server name |
| Load balancing | Least connections (default), round robin, least traffic, adaptive and IP hash; member weights, backup and draining members, sticky cookie or IP affinity |
| Load balancing | Least connections (default), round robin, least traffic, adaptive, random (two choices), consistent hash of path / URI / host / header / cookie / query parameter / client IP with optional bounded load, and IP hash; member weights, backup and draining members, sticky cookie or IP affinity; per-location backend groups with their own algorithm (HAProxy `use_backend` style); in-panel distribution simulator. Conditional routing: locations and whole-host rules selected by header, cookie, query parameter, method, client IP/CIDR, host or country (AND of conditions, negation, regex), with an in-panel routing tester. See [Load balancing](LOAD_BALANCING.md) |
| Health checks | Active TCP or HTTP probes with thresholds, optional separate probe port, expected response text and live health status per member |
| Connection reuse | Bounded keep-alive pools with idle and age limits, pool recycling and protocol telemetry |
| Custom locations | Prefix, exact and regex paths, path rewriting, per-location backends, Web Services, local responses, redirects and internal error fallbacks |
+2 -2
View File
@@ -79,7 +79,7 @@ The smallest useful file is a single vhost ([`examples/headless-minimal.json`](.
```
- Up to 32 backends per vhost. `allow_private` is required for loopback and private addresses.
- `algorithm`: `round_robin`, `least_connections` (default), `least_traffic`, `adaptive` or `ip_hash`; `sticky` sessions are configured as in [Vhosts](VHOSTS.md).
- `algorithm`: `round_robin`, `least_connections` (default), `least_traffic`, `adaptive`, `random`, `hash` (with a `hash` object: `source`, `name`, `path_depth`, `ignore_case`, `balance_factor`, `fallback`) or `ip_hash`; `sticky` sessions are configured as in [Vhosts](VHOSTS.md). Routes can set `backend_ids` and their own `load_balancing`; see [Load balancing](LOAD_BALANCING.md).
- By default requests with cookies or `Authorization` and responses with `Set-Cookie` are not cached, so enabling the cache for an application with logins only stores public responses and static files.
- With an HTTPS listener and the `*` host, clients that use an IP address or an unknown name receive the default certificate (self-signed unless `tls.default_certificate` points to your own).
@@ -383,7 +383,7 @@ curl -s http://127.0.0.1:9091/certificates | jq '.certificates[] | {id, source,
| Health checks / outlier detection | `health_check` (active), `passive_health` (ejection after real failures), `slow_start_seconds` |
| Retry policy | `retry` (`max_retries`, connect errors, timeouts, statuses) |
| Circuit breakers (`max_requests`, `max_pending_requests`) | backend `max_concurrent_requests` + `queue_timeout_ms`, vhost `rate_limit` |
| Sticky sessions / hash policy | `sticky`, `ip_hash` |
| Sticky sessions / hash policy | `sticky`, `ip_hash`, `hash` (consistent: path, header, cookie, query, IP; `balance_factor` for bounded load) |
| Admin `/ready`, `/clusters`, `/certs` | `/healthz` (pools), `/certificates` on `--health-listen`; Prometheus `/metrics` |
| Hot restart | `SIGHUP` reload without dropping connections; listener changes need a restart |
+136
View File
@@ -0,0 +1,136 @@
# Load balancing algorithms and location backend groups
Every reverse-proxy Vhost has one backend pool. Since 0.40.2 the pool can also balance by a **consistent hash of a request key** (path, URI, host, header, cookie, query parameter or client IP), and each **custom location** can send its requests to its own **backend group** with its **own algorithm** — the RustProxy equivalent of a HAProxy `use_backend` rule pointing at a backend with a different `balance` line.
Configure it in the panel under **Vhosts → Edit → Backends → Balancing** (whole Vhost) and **Vhosts → Edit → Custom locations → Backends & balancing** (one location).
## Algorithms
| `algorithm` | Behaviour | HAProxy equivalent |
|---|---|---|
| `least_connections` (default) | Fewest in-flight requests per weight. | `balance leastconn` |
| `round_robin` | Smooth weighted round robin. | `balance roundrobin` |
| `least_traffic` | Fewest bytes per second (EWMA) per weight. | — |
| `adaptive` | In-flight requests × measured latency + traffic, per weight. | — |
| `random` | Two random members, the less loaded one wins (power of two choices). | `balance random(2)` |
| `hash` | Consistent hash of the key configured in `hash`. | `balance hash …` / `uri` / `hdr()` / `url_param` + `hash-type consistent` |
| `ip_hash` | Consistent hash of the client address (kept for compatibility; equivalent to `hash` with `source: "ip"`). | `balance source` + `hash-type consistent` |
Weights, `backup`, `drain`, health checks, passive ejection, slow start and concurrency limits apply to every algorithm.
## Consistent hashing (`hash`)
RustProxy ranks the members for each key with **weighted rendezvous hashing** (highest random weight). Hashing is always consistent — there is no map-based mode:
- the same key always selects the same member while that member is eligible;
- when a member fails, is drained, disabled or removed, **only the keys of that member move**, and they return when it recovers;
- a member with weight 3 receives about three times as many keys as a member with weight 1;
- when the preferred member is at its `max_concurrent_requests` limit the next member in the key's order is used for that request.
`load_balancing.hash` settings (all optional):
| Field | Default | Meaning |
|---|---|---|
| `source` | `path` | `path` (path without query, as received from the client, before location rewrites), `uri` (path + query string), `host` (host name without port), `header`, `cookie`, `query` (one query parameter) or `ip` (client address seen by RustProxy). |
| `name` | — | Header, cookie or query parameter name; required for `header`, `cookie` and `query`, rejected otherwise. Header values from repeated lines are joined with `,`; the first matching cookie/parameter is used; values are not URL-decoded. |
| `path_depth` | `0` | For `path`/`uri`: hash only the first N directories (`/music/album/01.mp3` with depth 2 hashes `/music/album`), so a whole directory stays on one member. `0` hashes the whole path. Range 0–32. |
| `ignore_case` | `false` | Lower-case the key before hashing (useful for file names that differ only in case). |
| `balance_factor` | `0` | Consistent hashing with bounded loads, like HAProxy `hash-balance-factor`: a member may take a new request only while its in-flight requests stay within this percentage of its weighted share of the pool load; otherwise the next member for that key is used. `0` disables the bound; otherwise 101–1000 (125 is a common choice). Hot keys spill over deterministically and return when the load drops. |
| `fallback` | `round_robin` | Algorithm for requests without a key value (missing header, cookie or parameter): `round_robin`, `least_connections`, `least_traffic`, `adaptive` or `random`. |
Sticky affinity, when enabled, takes precedence over the algorithm: an `ip_hash` sticky mode always hashes the client address, and a valid affinity cookie selects its member before hashing.
The client IP is the transport peer (or the address accepted from trusted forwarding settings); `X-Forwarded-For` sent by a client cannot change it.
### Example: the whole Vhost hashes by path
```json
"load_balancing": {
"algorithm": "hash",
"hash": { "source": "path", "ignore_case": true, "balance_factor": 150 },
"health_check": { "mode": "http", "path": "/health" }
}
```
### Example: per-tenant routing by header, round robin without the header
```json
"load_balancing": {
"algorithm": "hash",
"hash": { "source": "header", "name": "X-Tenant", "fallback": "least_connections" }
}
```
## Location backend groups
A custom location with the **Proxy** action chooses its backends with `backend_ids` and, optionally, its own balancing with `load_balancing`:
| Location field | Meaning |
|---|---|
| `backend_id` | Pin one backend (unchanged). Cannot be combined with the two fields below. |
| `backend_ids` | Backend group: ids of Vhost backends (up to 64, no duplicates). Empty means the whole Vhost pool. Members whose `pool_eligible` is `false` (“Include in the default load-balancing pool” off) are used **only** by locations that list them. |
| `load_balancing` | Location balancing: `algorithm`, `hash` (same fields as above) and `sticky` (`off` default, `cookie` or `ip_hash`). Without it the location inherits the Vhost algorithm, hash settings and affinity. |
Members are shared with the Vhost pool: active and passive health, ejection, draining, concurrency limits, retries, slow start and statistics are the same objects, and the **Backends** status view shows them once. Retries stay within the location's group. A location affinity cookie is named `<vhost cookie>__<location id>` so it never competes with the Vhost cookie, and affinity cookies of the Vhost and its locations are stripped before requests reach an origin.
### Example: HAProxy `use_backend mp3_shards if is_mp3` with `balance hash path`
HAProxy:
```
frontend https_front
acl is_mp3 path_end -i .mp3
use_backend mp3_shards if is_mp3
backend mp3_shards
balance hash path
hash-type consistent
server mp3_1 10.0.0.11:80 check
server mp3_2 10.0.0.12:80 check
server mp3_3 10.0.0.13:80 check
```
RustProxy Vhost:
```json
{
"id": "music",
"frontend": { "hosts": ["music.example.com"], "listener_ids": ["https"] },
"backends": [
{ "id": "app", "url": "http://10.0.0.5:8080", "allow_private": true },
{ "id": "mp3_1", "url": "http://10.0.0.11:80", "allow_private": true, "pool_eligible": false },
{ "id": "mp3_2", "url": "http://10.0.0.12:80", "allow_private": true, "pool_eligible": false },
{ "id": "mp3_3", "url": "http://10.0.0.13:80", "allow_private": true, "pool_eligible": false }
],
"load_balancing": { "algorithm": "least_connections", "health_check": { "mode": "tcp" } },
"routes": [
{
"id": "mp3",
"match_type": "regex_insensitive",
"path_prefix": "\\.mp3$",
"backend_ids": ["mp3_1", "mp3_2", "mp3_3"],
"load_balancing": { "algorithm": "hash", "hash": { "source": "path" } }
}
]
}
```
`path_end -i .mp3` becomes a case-insensitive regex location; `check` corresponds to the Vhost health check (TCP by default). Everything else on the host keeps using `app` with least connections.
In the panel: add the three backends with **Include in the default load-balancing pool** off, add a custom location, choose **Backends → Backend group**, tick the three backends, turn on **Own balancing for this location** and click **Files / cache shards by path**.
Locations can additionally require request conditions (header, cookie, query parameter, method, client IP, host, country), and a match type `any` turns a location into a rule for the whole host — together the full HAProxy `use_backend <group> if <acls>` pattern. See [Custom locations → Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip).
## Panel helpers
- **Quick setup** buttons fill typical combinations: files by path, session cookie, tenant header, query parameter, client IP, or even load spreading.
- Each algorithm shows a short explanation, and hash settings show the **HAProxy equivalent** lines for comparison.
- **Test distribution** runs in the browser on the unsaved draft. Paste sample paths, URLs or key values to see the hash key and the selected backend for each, the share per backend, and — after ticking **Simulate failure of** — which keys would move. The simulator uses the same SHA-256 rendezvous scoring as the proxy (checked by `tools/dev/test_balance_simulator.js`); load-based algorithms show the expected share by weight instead. It does not account for current concurrency limits, bounded-load spill-over or live health.
## Compatibility and limits
- Configurations without `hash`, `backend_ids` or location `load_balancing` load and behave exactly as before; these fields are omitted when unset, so saved files stay unchanged. `ip_hash` keeps the same client → backend mapping as earlier versions.
- A configuration that uses the new fields is rejected by 0.40.1 and older.
- Hashing reads the request as received. Changing a member id changes its keys; renaming the Vhost id reshuffles all keys (the Vhost id is part of the hash input).
- Consistent hashing spreads **keys**, not requests: a few very popular keys still load their members more. Use `balance_factor` for hot keys, or weights.
- Headless JSON uses the same fields; the panel and API validate them before activation.
+2 -1
View File
@@ -22,7 +22,8 @@ Guides for operating RustProxy: installation, publishing services, security, cer
## Publishing services
- [Vhosts and backends](VHOSTS.md) — domains, listeners, backends, balancing, health checks and redirects.
- [Custom locations](CUSTOM_LOCATIONS.md) — path routing, rewrites, local responses and error fallbacks.
- [Custom locations](CUSTOM_LOCATIONS.md) — path routing, request conditions (header, cookie, IP, method, country), whole-host rules, rewrites, local responses and error fallbacks.
- [Load balancing](LOAD_BALANCING.md) — algorithms, consistent hashing by path/header/cookie/query/IP, location backend groups and the distribution simulator.
- [Web Server](WEB_SERVER.md) — static sites, downloads, `try_files`, rewrites, `.htaccess` subset and error pages.
- [PHP-FPM](PHP_FPM.md) — PHP profiles, pool isolation and application examples.
- [HTTP transport and TLS](TRANSPORT.md) — HTTPS, HTTP/2, HTTP/3, WebSockets, backend protocols and post-quantum key exchange.
+2 -2
View File
@@ -53,7 +53,7 @@ Under **Vhosts → Edit → Security → Country access**, choose `Off`, `Block`
- **Reverse Proxy:** one Vhost has a backend pool. Each member has a configured URL, ID, enabled flag, weight, optional backup/drain state, health settings and capacity limits.
- **Web Server:** Vhost references a Web Service by ID. Its document root, directory handling, PHP options and static-file headers remain configured under **Web Server**.
- **Custom locations:** can override selected URL paths and use the default pool, a pinned backend, a different Web Service, a redirect or a local response. Unmatched paths still use the main source.
- **Custom locations:** can override selected URL paths and use the default pool, a backend group with its own balancing, a pinned backend, a different Web Service, a redirect or a local response. Unmatched paths still use the main source. Locations and whole-host rules can also require conditions on headers, cookies, query parameters, method, client IP, host or country — see [Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip).
Sample documents in `examples/vhosts-private.json` and `examples/vhosts-balanced.json` illustrate JSON formats, but their IP addresses, certificates and health endpoints are examples only.
@@ -72,7 +72,7 @@ Connection reuse is bounded by configured idle-pool/recycle limits. The default
## Load balancing and health
Backend pools support scheduling/weighting, standby members, draining and optional session affinity. Check the **Backends** status view for member health, recently observed HTTP response code, upstream protocol and resource usage. A reported status from normal traffic is not necessarily the result of a health probe.
Backend pools support scheduling/weighting, standby members, draining and optional session affinity. Algorithms are least connections (default), round robin, least traffic, adaptive, random (two choices), consistent hash of a request key (path, URI, host, header, cookie, query parameter or client IP, with optional bounded load) and IP hash; a custom location can use its own backend group and algorithm. See [Load balancing](LOAD_BALANCING.md), including a HAProxy `use_backend` + `balance hash path` example and the panel's distribution simulator. Check the **Backends** status view for member health, recently observed HTTP response code, upstream protocol and resource usage. A reported status from normal traffic is not necessarily the result of a health probe.
- Health monitoring may use TCP or HTTP checks with a path, Host, interval and thresholds. Avoid write endpoints; use a lightweight `/health` or equivalent.
- **Health check port** (`health_check.port`) probes a different port than the one receiving traffic, like `check port` in HAProxy. Example: a backend serving traffic on `http://10.0.0.5:80` with a status endpoint on port `8079` uses `"health_check": {"mode": "http", "path": "/status", "port": 8079}`. The probe keeps the backend host, scheme, TLS settings and address restrictions; only the port changes. Leave it empty to probe the traffic port. The port can be set for the whole pool or per backend.