Sub topic 8
Matching by hostname, path, header, query, and method
This chapter assumes you can read an HTTPRoute, know how parentRefs attach a route to a Gateway, and understand basic HTTP: hosts, paths, headers, query strings, and methods.
Two levels of matching
An HTTPRoute narrows traffic in two steps. First, spec.hostnames filters by the request's host. Then each entry in spec.rules has a matches list that filters by path, headers, query parameters, and method.
- Fields inside one match are combined with AND. Every field must be true.
- Entries in the
matcheslist are combined with OR. Any one match is enough. - If a rule has no
matches, it behaves as a match on path prefix/.
Hostnames
hostnames accepts exact names such as shop.example.com and wildcards such as *.example.com. A wildcard matches one or more leading labels. The listener's own hostname also applies, so a route only receives requests that satisfy both.
A rule with every match type
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop-matching
namespace: shop-team
spec:
parentRefs:
- name: web-gateway
namespace: infra
hostnames:
- shop.example.com
rules:
- matches:
- path:
type: PathPrefix
value: /api
headers:
- name: x-env
value: beta
queryParams:
- name: version
value: "2"
method: GET
backendRefs:
- name: shop-v2
port: 8080
- matches:
- path:
type: Exact
value: /healthz
backendRefs:
- name: shop-v1
port: 8080The first rule sends a request to shop-v2 only if the path starts with /api, the header x-env equals beta, the query has version=2, and the method is GET. The second rule matches only the exact path /healthz.
Path match types
| Type | Behavior |
|---|---|
| `Exact` | The whole path must equal the value. |
| `PathPrefix` | Matches on path elements. `/cart` matches `/cart` and `/cart/items`, but not `/cartoons`. |
| `RegularExpression` | Implementation-specific. Portability is not guaranteed. |
Header and query matches default to Exact. Header names are case-insensitive, but values are not.
Precedence
When several rules match one request, the Gateway API picks a winner in this order:
- Exact path match.
- Longest prefix path match.
- Method match.
- Largest number of header matches.
- Largest number of query parameter matches.
If routes still tie, the oldest route by creation time wins, then the first by namespace/name alphabetical order.
Exercise
A route has one rule with two entries in matches. The first has path: /a and method: POST. The second has path: /b. Which requests does the rule accept?
Show answer
A POST request to a path starting with /a, or any request (any method) to a path starting with /b. Fields inside one match are ANDed, and separate matches are ORed.
Exercise
Two rules match a request to /api/users. Rule 1 is PathPrefix /api. Rule 2 is PathPrefix /api/users. Which wins, and why?
Show answer
Rule 2. Both match, but the longer prefix is more specific, so it takes precedence.