Routes
Define HTTPRoutes for HAProxy Unified Gateway
The Gateway API defines specialized resources for routing different types of network traffic. You would use an HTTPRoute resource to route HTTP traffic. HTTPRoutes use routing rules to define how incoming HTTP requests should be forwarded to backend applications based on attributes such as hostname and/or URL path.
Prerequisites checklist Jump to heading
Before continuing, ensure that you’ve met these prerequisites:
- Define a Gateway. When defining a Gateway, add an HTTP and/or HTTPS listener that sets its
allowedRoutesproperty to accept routes of kindHTTPRoute.
Define routing rules Jump to heading
In your HTTPRoutes, you’ll define rules for routing HTTP requests to your backend applications. These rules include match conditions for hostnames and/or URL paths. Hostname-based routing is useful when you want to route traffic based on the domain. For example, you want to route traffic for api.example.com and web.example.com to different services. Path-based routing is useful when you have multiple applications under the same domain and want to route traffic based on the URL path. For example, you want to route traffic for example.com/web.
Tip
You can combine hostname-based routing rules and path-based routing rules.
Implement hostname-based routing Jump to heading
You can configure hostname matching in three ways:
| Match type | Match behavior |
|---|---|
| No hostname | Matches all hostnames accepted by the Gateway. |
| Exact hostname | Matches only this domain. Requests to other domains or subdomains are filtered out. Example: web.example.com matches requests only to that subdomain. |
| Wildcard hostname | Matches all subdomains. Example: *.example.com. This doesn’t match requests to the root domain; add an additional entry to hostnames in the HTTPRoute if you want to include the root domain. |
The following steps show how to specify the hostname(s) at which the HTTPRoute will accept traffic for forwarding:
-
For exact hostname and wildcard hostname matching: If your Gateway resource sets a
hostnamefield, update it and omit or comment outhostname. This ensures that the Gateway will relay traffic for all of your domains. You’ll filter by hostname in the HTTPRoute resource.gateway.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: Gatewaymetadata:name: example-haproxy-gatewaynamespace: defaultspec:gatewayClassName: haproxylisteners:- name: httpprotocol: HTTPport: 31080# hostname: "example.com"allowedRoutes:kinds:- group: gateway.networking.k8s.iokind: HTTPRoutenamespaces:from: Samegateway.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: Gatewaymetadata:name: example-haproxy-gatewaynamespace: defaultspec:gatewayClassName: haproxylisteners:- name: httpprotocol: HTTPport: 31080# hostname: "example.com"allowedRoutes:kinds:- group: gateway.networking.k8s.iokind: HTTPRoutenamespaces:from: Same -
Apply the changes with
kubectl:nixkubectl apply -f gateway.yamlnixkubectl apply -f gateway.yamloutputtextgateway.gateway.networking.k8s.io/example-haproxy-gateway configuredoutputtextgateway.gateway.networking.k8s.io/example-haproxy-gateway configured -
Define an HTTPRoute resource for your target domain(s). In this example, we route traffic for the hostname
web.example.com.Section Description parentRefs References one or more Gateways to which an HTTPRoute tries to attach. This HTTPRoute will attach to Gatewayresources that have listeners withallowedRoutesmatching theHTTPRoutekind and a matching namespace. ThesectionNamefield specifies the name of the listener on the Gateway to attach to. In this example, we attach to the HTTP listener, but you could attach to the HTTPS listener.hostnames Lists hostnames to accept traffic for. You can list multiple hostnames in this section. Alternatively, you can specify the wildcard *.example.com, for example, to match all subdomains. Omitting this field entirely indicates that you want to match all domains the Gateway accepts.rules Each entry has a backendRefssection to route to the specified service. For example, requests forweb.example.comwill route toweb-svc. AbackendRefsentry refers to the name of a Service resource and its listening port.web-hostname-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: web-hostname-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- web.example.comrules:- backendRefs:- name: web-svcnamespace: defaultport: 80web-hostname-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: web-hostname-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- web.example.comrules:- backendRefs:- name: web-svcnamespace: defaultport: 80 -
Apply the changes with
kubectl:nixkubectl apply -f web-hostname-route.yamlnixkubectl apply -f web-hostname-route.yamloutputtexthttproute.gateway.networking.k8s.io/web-hostname-route createdoutputtexthttproute.gateway.networking.k8s.io/web-hostname-route created -
If your HTTPRoute resource lists a
backendRefsService that’s in a namespace that’s different from the namespace where the HTTPRoute is defined, you’ll need to add a ReferenceGrant for cross-namespace service references.
Implement path-based routing Jump to heading
Migrating from Ingress API
Path-based routing with Gateway API behaves similarly to traditional Ingress rules. This makes it easy to migrate from HAProxy Kubernetes Ingress Controller or other Ingress controller implementations.
HTTPRoute supports three URL path matching strategies:
| Match type | Match behavior |
|---|---|
Exact |
Matches only a single path. For example: /web; this doesn’t match /web/ or /web/v1. |
PathPrefix |
Matches a path and all of its subpaths. For example: /web, /web/app. |
RegularExpression |
Matches using a regular expression. For example: ^/web/.* to match any path beginning with /web/. |
Tip
Use PathPrefix for most routing applications. Use Exact for single endpoints (such as /health) and RegularExpression only for advanced cases.
To implement path-based routing:
-
Define an HTTPRoute for routing HTTP traffic for the target URL paths. In this example, we route traffic for the path
/web.Section Description parentRefs References one or more Gateways to which an HTTPRoute tries to attach. This HTTPRoute will attach to Gatewayresources that have listeners withallowedRoutesmatching theHTTPRoutekind and a matching namespace. ThesectionNamefield specifies the name of the listener on the Gateway to attach to. In this example, we attach to the HTTP listener, but you could attach to the HTTPS listener.rules Each entry has a matchesandbackendRefssection. In this example, we set thetypeof the path-matching rule toPathPrefix. This means that URL paths that begin with the specifiedvaluewill be routed to the service specified by thebackendRefsentry. For example, requests beginning with/webwill route toweb-svc. You can specifyExactto match only a single path specified byvalue, or specifyRegularExpressionand specify a regular expression invaluefor more complicated matching. AbackendRefsentry refers to the name of a Service resource and its listening port.path-based-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: path-based-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerrules:- matches:- path:type: PathPrefixvalue: /webbackendRefs:- name: web-svcnamespace: defaultport: 80path-based-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: path-based-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerrules:- matches:- path:type: PathPrefixvalue: /webbackendRefs:- name: web-svcnamespace: defaultport: 80 -
Apply the changes with
kubectl:nixkubectl apply -f path-based-route.yamlnixkubectl apply -f path-based-route.yamloutputtexthttproute.gateway.networking.k8s.io/path-based-route createdoutputtexthttproute.gateway.networking.k8s.io/path-based-route created -
Optional: If your HTTPRoute resource lists a
backendRefsService that’s in a namespace that’s different from the namespace where the HTTPRoute is defined, you’ll need to add a ReferenceGrant for cross-namespace service references. -
Optional: When using path-based routing, you may want to restrict which hostnames your Gateway will accept traffic for.
-
Update your Gateway resource to set the
hostnamefield on the listener.gateway.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: Gatewaymetadata:name: example-haproxy-gatewaynamespace: defaultspec:gatewayClassName: haproxylisteners:- name: httpprotocol: HTTPport: 31080hostname: "example.com"allowedRoutes:kinds:- group: gateway.networking.k8s.iokind: HTTPRoutenamespaces:from: Samegateway.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: Gatewaymetadata:name: example-haproxy-gatewaynamespace: defaultspec:gatewayClassName: haproxylisteners:- name: httpprotocol: HTTPport: 31080hostname: "example.com"allowedRoutes:kinds:- group: gateway.networking.k8s.iokind: HTTPRoutenamespaces:from: Same -
Apply the changes with
kubectl:nixkubectl apply -f gateway.yamlnixkubectl apply -f gateway.yamloutputtextgateway.gateway.networking.k8s.io/example-haproxy-gateway configuredoutputtextgateway.gateway.networking.k8s.io/example-haproxy-gateway configured
-
-
Optional: To test connectivity with the Gateway and HTTPRoute you just defined, deploy the example application using Deployment and Service resources. The application uses the
hashicorp/http-echoDocker container image. It’ll receive HTTP traffic on port 5678 and respond with text indicating the application’s name.Note that the Service is named
web-svc, which is the same Service name you specified when you defined your HTTPRoute in the previous steps, and it listens on port 80. This is how the HTTPRoute knows the Service to route to.app.yamlyamlapiVersion: apps/v1kind: Deploymentmetadata:name: web-svcnamespace: defaultspec:replicas: 1selector:matchLabels:app: web-svctemplate:metadata:labels:app: web-svcspec:containers:- name: webimage: hashicorp/http-echo:0.2.3args: ["-text=WEB RESPONSE"]ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: web-svcnamespace: defaultspec:selector:app: web-svcports:- port: 80targetPort: 5678app.yamlyamlapiVersion: apps/v1kind: Deploymentmetadata:name: web-svcnamespace: defaultspec:replicas: 1selector:matchLabels:app: web-svctemplate:metadata:labels:app: web-svcspec:containers:- name: webimage: hashicorp/http-echo:0.2.3args: ["-text=WEB RESPONSE"]ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: web-svcnamespace: defaultspec:selector:app: web-svcports:- port: 80targetPort: 5678Apply the changes with
kubectl:nixkubectl apply -f app.yamlnixkubectl apply -f app.yamloutputtextdeployment.apps/web-svc createdservice/web-svc createdoutputtextdeployment.apps/web-svc createdservice/web-svc created
Implement weighted traffic splitting Jump to heading
Use weighted traffic splitting when you want different percentages of traffic to route to different services. One use case is canary deployments. A canary deployment means routing a small percentage of traffic to the new version of your application, and then gradually ramping up, allowing you to release the new version in the safest possible way.
-
Define an HTTPRoute for routing HTTP traffic to your service.
Section Description parentRefs References one or more Gateways to which the HTTPRoute wants to attach, which in this case is example-haproxy-gateway. ThesectionNamefield specifies the name of the listener on the Gateway to attach to.hostnames We’re using hostname-based routing, so we’re including the hostnamessection. In this example, we attach to the HTTP listener, but you could attach to the HTTPS listener.rules Lists two services, blueandgreen. Theblueservice will receive 90% of the traffic and thegreenservice will receive 10% of the traffic.canary-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: canary-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"rules:- backendRefs:- name: bluenamespace: defaultport: 80weight: 9- name: greennamespace: defaultport: 80weight: 1canary-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: canary-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"rules:- backendRefs:- name: bluenamespace: defaultport: 80weight: 9- name: greennamespace: defaultport: 80weight: 1 -
Apply the changes with
kubectl:nixkubectl apply -f canary-route.yamlnixkubectl apply -f canary-route.yamloutputtexthttproute.gateway.networking.k8s.io/canary-route createdoutputtexthttproute.gateway.networking.k8s.io/canary-route created -
Optional: To test connectivity with the Gateway and HTTPRoute, deploy two test applications using Deployments and Services. Here, we define two example applications using the
hashicorp/http-echoDocker container image. They will each receive HTTP traffic on port 5678 and respond with text indicating receipt of the request.Note that the Services are named
blueandgreen, the same Service names you specified when you defined your HTTPRoute in the previous steps, both listening on port 80, which you defined in the HTTPRoute as well. This is how the HTTPRoute knows the Service to route to.apps.yamlyamlapiVersion: apps/v1kind: Deploymentmetadata:name: bluenamespace: defaultspec:replicas: 1selector:matchLabels:app: bluetemplate:metadata:labels:app: bluespec:containers:- name: blueimage: hashicorp/http-echoargs:- "-text=Hello from blue"ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: bluenamespace: defaultspec:selector:app: blueports:- port: 80targetPort: 5678---apiVersion: apps/v1kind: Deploymentmetadata:name: greennamespace: defaultspec:replicas: 1selector:matchLabels:app: greentemplate:metadata:labels:app: greenspec:containers:- name: greenimage: hashicorp/http-echoargs:- "-text=Hello from green"ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: greennamespace: defaultspec:selector:app: greenports:- port: 80targetPort: 5678apps.yamlyamlapiVersion: apps/v1kind: Deploymentmetadata:name: bluenamespace: defaultspec:replicas: 1selector:matchLabels:app: bluetemplate:metadata:labels:app: bluespec:containers:- name: blueimage: hashicorp/http-echoargs:- "-text=Hello from blue"ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: bluenamespace: defaultspec:selector:app: blueports:- port: 80targetPort: 5678---apiVersion: apps/v1kind: Deploymentmetadata:name: greennamespace: defaultspec:replicas: 1selector:matchLabels:app: greentemplate:metadata:labels:app: greenspec:containers:- name: greenimage: hashicorp/http-echoargs:- "-text=Hello from green"ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: greennamespace: defaultspec:selector:app: greenports:- port: 80targetPort: 5678 -
Apply the changes with
kubectl:nixkubectl apply -f apps.yamlnixkubectl apply -f apps.yamloutputtextdeployment.apps/blue createdservice/blue createddeployment.apps/green createdservice/green createdoutputtextdeployment.apps/blue createdservice/blue createddeployment.apps/green createdservice/green created
Enable CORS Jump to heading
Web browsers have a security feature that prevents unauthorized websites from accessing data belonging to other websites. It’s named the Same-origin policy and it restricts who can read or write data, based on the website’s domain name.
For example, if trusted-bank.com hosts a URL /account-details, it’s probable that requests to that URL should originate only from trusted-bank.com. If bad-guy.com secretly makes an asynchronous HTTP request to that URL in an attempt to retreive the account details of a person who is tricked into visiting bad-guy.com, the browser will stop bad-guy.com from reading the response. This protection is on by default. However, in some cases, you’ll want to permit other origins to access your data.
Several examples:
- From one domain, such as
www.trusted-bank.com, you want to use Javascript to make HTTP requests to a web API hosted at another domain, such asapi.trusted-bank.com. - From your website, which is hosted at TCP port 80, you want to use Javascript to make HTTP requests to a web API hosted at a different port, such as 8080. The differences in port count as different origins.
- You host a web API that you’d like to allow anyone to use to get data, without restrictions.
In cases like these, you’ll want to configure Cross-Origin Resource Sharing (CORS). With CORS, you can relax the Same-origin policy restrictions:
- Add origins to an allowlist. They’ll be returned to the browser in an
Access-Control-Allow-Originheader. - Name which HTTP methods are allowed, such as
GET,POST, andDELETE, in response to a preflight request. These will be returned to the browser in anAccess-Control-Allow-Methodsheader. - Name which request headers are allowed, which will be returned in an
Access-Control-Allow-Headersheader. - Name which headers the server can return in the response, which will be returned in an
Access-Control-Expose-Headersheader. - Set whether credentials can be included in the request. This will be returned in an
Access-Control-Allow-Credentialsheader. - Set how long the results of a preflight request can be cached. This will be returned in an
Access-Control-Max-Ageheader.
To configure CORS:
-
Define an HTTPRoute for routing HTTP traffic to your service. Include a filter of type
CORS, then include acorssection with the CORS properties. You can setallowOrigins,allowMethods,allowHeaders, andexposeHeaderseach to a single asterisk (*), which allows all.cors-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: cors-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- api.example.comrules:- backendRefs:- name: api-servicenamespace: defaultport: 8080filters:- type: CORScors:allowOrigins:- https://www.foo.com- https://www.bar.com- https://*.baz.com- http://fiz.com:8080allowMethods:- GET- DELETE- POST- PUTallowHeaders:- X-Request-Header1- X-Request-Header2exposeHeaders:- X-Response-Header3- X-Response-Header4allowCredentials: truemaxAge: 3600cors-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: cors-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- api.example.comrules:- backendRefs:- name: api-servicenamespace: defaultport: 8080filters:- type: CORScors:allowOrigins:- https://www.foo.com- https://www.bar.com- https://*.baz.com- http://fiz.com:8080allowMethods:- GET- DELETE- POST- PUTallowHeaders:- X-Request-Header1- X-Request-Header2exposeHeaders:- X-Response-Header3- X-Response-Header4allowCredentials: truemaxAge: 3600 -
Apply the changes with
kubectl:nixkubectl apply -f cors-route.yamlnixkubectl apply -f cors-route.yamloutputtexthttproute.gateway.networking.k8s.io/cors-route createdoutputtexthttproute.gateway.networking.k8s.io/cors-route created
Add a ReferenceGrant for cross-namespace service references Jump to heading
If your HTTPRoute lists a Service under backendRefs that’s in a different namespace than the HTTPRoute resource, you’ll need to define a ReferenceGrant resource to allow cross-namespace communication between the HTTPRoute and the Service.
Below, we allow an HTTPRoute in the default namespace to reference a Service in the foo namespace. Note that the to section doesn’t need a namespace because a ReferenceGrant can refer only to resources defined in its own namespace.
foo-referencegrant.yamlyamlapiVersion: gateway.networking.k8s.io/v1alpha2kind: ReferenceGrantmetadata:name: refgrantns1namespace: foospec:from:- group: "gateway.networking.k8s.io"kind: "HTTPRoute"namespace: defaultto:- group: ""kind: "Service"
foo-referencegrant.yamlyamlapiVersion: gateway.networking.k8s.io/v1alpha2kind: ReferenceGrantmetadata:name: refgrantns1namespace: foospec:from:- group: "gateway.networking.k8s.io"kind: "HTTPRoute"namespace: defaultto:- group: ""kind: "Service"
Apply the changes with kubectl:
nixkubectl apply -f foo-referencegrant.yaml
nixkubectl apply -f foo-referencegrant.yaml
Redirect to HTTPS Jump to heading
You can use a RequestRedirect filter to redirect a request from HTTP to HTTPS. You shouldn’t use this in combination with the URLRewrite filter.
To redirect requests from HTTP to HTTPS:
-
Check that your gateway has HTTP and HTTPS listeners.
-
Add two HTTPRoute resources:
-
The first uses a
RequestRedirectfilter to redirect HTTP requests to the HTTPS scheme. It also setsportto the nodePort where the gateway’s HTTPS listener is listening. In this case, that’s nodePort 31443. -
The second HTTPRoute resource receives the HTTPS traffic and relays it to the backend application.
redirect-to-https-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: redirect-to-https-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "payments.example.com"rules:- filters:- type: RequestRedirectrequestRedirect:scheme: httpsport: 31443statusCode: 302---apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: https-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: https-listenerhostnames:- "payments.example.com"rules:- backendRefs:- name: payments-svcnamespace: defaultport: 80redirect-to-https-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: redirect-to-https-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "payments.example.com"rules:- filters:- type: RequestRedirectrequestRedirect:scheme: httpsport: 31443statusCode: 302---apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: https-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: https-listenerhostnames:- "payments.example.com"rules:- backendRefs:- name: payments-svcnamespace: defaultport: 80 -
-
Apply the changes with
kubectl:nixkubectl apply -f redirect-to-https-route.yamlnixkubectl apply -f redirect-to-https-route.yamloutputtexthttproute.gateway.networking.k8s.io/redirect-to-https-route createdhttproute.gateway.networking.k8s.io/https-route createdoutputtexthttproute.gateway.networking.k8s.io/redirect-to-https-route createdhttproute.gateway.networking.k8s.io/https-route created
Redirect to a different hostname Jump to heading
You can use a RequestRedirect filter to redirect a request to a different DNS hostname. For example, you can redirect from example.com to www.example.com. You shouldn’t use this in combination with the URLRewrite filter.
To redirect requests to a different hostname:
-
Add two HTTPRoute resources:
-
The first HTTPRoute resource matches the hostname
example.com. It uses aRequestRedirectfilter to redirect to thewww.example.comhostname. It also setsportto the nodePort where the gateway’s HTTP listener is listening. In this case, that’s nodePort 31080. -
The second HTTPRoute resource matches the hostname
www.example.com. It receives the request and relays it to the backend application.
redirect-hostname-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: hostname-redirectnamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"rules:- filters:- type: RequestRedirectrequestRedirect:scheme: httphostname: "www.example.com"port: 31080statusCode: 302---apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: www-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "www.example.com"rules:- backendRefs:- name: www-svcnamespace: defaultport: 80redirect-hostname-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: hostname-redirectnamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"rules:- filters:- type: RequestRedirectrequestRedirect:scheme: httphostname: "www.example.com"port: 31080statusCode: 302---apiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: www-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "www.example.com"rules:- backendRefs:- name: www-svcnamespace: defaultport: 80 -
-
Apply the changes with
kubectl:nixkubectl apply -f redirect-hostname-route.yamlnixkubectl apply -f redirect-hostname-route.yamloutputtexthttproute.gateway.networking.k8s.io/hostname-redirect createdhttproute.gateway.networking.k8s.io/www-route createdoutputtexthttproute.gateway.networking.k8s.io/hostname-redirect createdhttproute.gateway.networking.k8s.io/www-route created
Redirect to a different URL path Jump to heading
You can use a RequestRedirect filter to redirect a request to a different URL path. For example, suppose that you wanted to give a simple way for users to get to the latest documentation of your API. You could redirect from the path /api/latest to whichever version was the latest one, such as /api/v2. Then, later, to /api/v3 and so on.
To redirect requests to a different URL path:
-
Add one HTTPRoute resource that has two rules.
-
The first rule matches URL paths prefixed with
/api/latest. It uses aRequestRedirectfilter to redirect the request to the URL path/api/v2. In this example, we’re using the filter typeReplacePrefixMatch, which replaces only the prefix in the URL path, preserving the rest of the URL path and arguments. You can also set type toReplaceFullPathand setreplaceFullPathto the URL path that will replace the entire path. -
The second rule matches requests that have URL paths prefixed with
/api/v2and relays them to the backend application.
redirect-path-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: redirect-path-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"- "www.example.com"rules:- matches:- path:type: PathPrefixvalue: /api/latestfilters:- type: RequestRedirectrequestRedirect:scheme: httppath:type: ReplacePrefixMatchreplacePrefixMatch: /api/v2port: 31080statusCode: 302- matches:- path:type: PathPrefixvalue: /api/v2backendRefs:- name: api-v2-svcnamespace: defaultport: 80redirect-path-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: redirect-path-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"- "www.example.com"rules:- matches:- path:type: PathPrefixvalue: /api/latestfilters:- type: RequestRedirectrequestRedirect:scheme: httppath:type: ReplacePrefixMatchreplacePrefixMatch: /api/v2port: 31080statusCode: 302- matches:- path:type: PathPrefixvalue: /api/v2backendRefs:- name: api-v2-svcnamespace: defaultport: 80 -
-
Apply the changes with
kubectl:nixkubectl apply -f redirect-path-route.yamlnixkubectl apply -f redirect-path-route.yamloutputtexthttproute.gateway.networking.k8s.io/redirect-path-route createdoutputtexthttproute.gateway.networking.k8s.io/redirect-path-route created
Rewrite the requested URL path Jump to heading
You may want to rewrite the URL path before forwarding the request to the backend, because:
- Your backend expects a specific URL structure.
- You want to hide internal routing details.
- You’re consolidating multiple backend services under a shared URL prefix.
- You want to expose a simpler API.
- You’re migrating legacy Ingress rules to Gateway API.
To rewrite the requested URL path:
-
Define an HTTPRoute for routing HTTP traffic to your service.
The path-matching rule specifies the
typeasPathPrefix. This means that for URL paths that begin with the specifiedvaluewill be routed to the corresponding service specified by thebackendRefsin the rule. There’s also afilteroftype: URLRewritethat instructs the HTTPRoute to replace/servicewith/.rewrite-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: rewrite-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerrules:- matches:- path:type: PathPrefixvalue: /servicefilters:- type: URLRewriteurlRewrite:path:type: ReplacePrefixMatchreplacePrefixMatch: /backendRefs:- name: rewrite-backend-svcnamespace: defaultport: 80rewrite-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: rewrite-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerrules:- matches:- path:type: PathPrefixvalue: /servicefilters:- type: URLRewriteurlRewrite:path:type: ReplacePrefixMatchreplacePrefixMatch: /backendRefs:- name: rewrite-backend-svcnamespace: defaultport: 80 -
Apply the changes with
kubectl:nixkubectl apply -f rewrite-route.yamlnixkubectl apply -f rewrite-route.yamloutputtexthttproute.gateway.networking.k8s.io/rewrite-route createdoutputtexthttproute.gateway.networking.k8s.io/rewrite-route created -
Optional: To test connectivity with the Gateway and HTTPRoute, deploy a test application using a Deployment and a Service. Here, we define an example application using the
hashicorp/http-echoDocker container image. It will receive HTTP traffic on port 5678 (the Gateway terminates the TLS connection and then communicates with backend services over HTTP) and respond with text indicating receipt of the request.Note that the Service is named
rewrite-backend-svc, the same Service name you specified when you defined your HTTPRoute in the previous steps, listening on port 80, which you defined in the HTTPRoute as well. This is how the HTTPRoute knows what Service to route to.apps.yamlyamlapiVersion: apps/v1kind: Deploymentmetadata:name: rewrite-backendnamespace: defaultspec:replicas: 1selector:matchLabels:app: rewrite-backendtemplate:metadata:labels:app: rewrite-backendspec:containers:- name: echoimage: hashicorp/http-echoargs:- "-text=Rewrite backend reached"ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: rewrite-backend-svcnamespace: defaultspec:selector:app: rewrite-backendports:- port: 80targetPort: 5678apps.yamlyamlapiVersion: apps/v1kind: Deploymentmetadata:name: rewrite-backendnamespace: defaultspec:replicas: 1selector:matchLabels:app: rewrite-backendtemplate:metadata:labels:app: rewrite-backendspec:containers:- name: echoimage: hashicorp/http-echoargs:- "-text=Rewrite backend reached"ports:- containerPort: 5678---apiVersion: v1kind: Servicemetadata:name: rewrite-backend-svcnamespace: defaultspec:selector:app: rewrite-backendports:- port: 80targetPort: 5678 -
Apply the changes with
kubectl:nixkubectl apply -f apps.yamlnixkubectl apply -f apps.yamloutputtextdeployment.apps/tls-test createdservice/tls-test-svc createdoutputtextdeployment.apps/tls-test createdservice/tls-test-svc created
Modify response headers Jump to heading
You can modify the HTTP headers that your application returns to the client by adding a ResponseHeaderModifier filter. You can add, set (overwrite), and remove headers.
To modify response headers:
-
Define an HTTPRoute for routing HTTP traffic to your service. Add a filter of type
ResponseHeaderModifier. Then, in theresponseHeaderModifiersection, defineadd,set, and/orremoverules. In this example, we add anX-Frame-Optionsheader, overwrite the value of theX-Powered-Byheader, and remove theServerheader.response-headers-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: response-headers-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- example.comrules:- backendRefs:- name: web-svcnamespace: defaultport: 80filters:- type: ResponseHeaderModifierresponseHeaderModifier:add:- name: X-Frame-Optionsvalue: DENYset:- name: X-Powered-Byvalue: unicornsremove:- Serverresponse-headers-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: response-headers-routenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- example.comrules:- backendRefs:- name: web-svcnamespace: defaultport: 80filters:- type: ResponseHeaderModifierresponseHeaderModifier:add:- name: X-Frame-Optionsvalue: DENYset:- name: X-Powered-Byvalue: unicornsremove:- Server -
Apply the changes with
kubectl:nixkubectl apply -f response-headers-route.yamlnixkubectl apply -f response-headers-route.yamloutputtexthttproute.gateway.networking.k8s.io/response-headers-route createdoutputtexthttproute.gateway.networking.k8s.io/response-headers-route created
Enable session persistence Jump to heading
When you enable session persistence, HAProxy Unified Gateway will place a cookie into the user’s browser that allows it to continue to route the user’s requests to the same backend pod that accepted the first request. This persistence will continue for the duration of the user’s session. This overrides the ordinary load balancing behavior so that the same pod can handle all of the user’s requests and maintain any in-memory state associated with that user. You won’t need this if your application is stateless.
To enable session persistence:
-
Define an HTTPRoute for routing HTTP traffic to your service. In this example, we enable cookie-based session persistence for the
web-svcbackend service by including asessionPersistenceblock. The session will persist for a maximum duration defined byabsoluteTimeout. It will also end if the user is idle for the duration defined byidleTimeout.http-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: session-persistencenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"rules:- backendRefs:- name: web-svcnamespace: defaultport: 80sessionPersistence:type: CookiesessionName: "sticky-cookie"absoluteTimeout: 1hidleTimeout: 10mcookieConfig:lifetimeType: Sessionhttp-route.yamlyamlapiVersion: gateway.networking.k8s.io/v1kind: HTTPRoutemetadata:name: session-persistencenamespace: defaultspec:parentRefs:- name: example-haproxy-gatewaysectionName: http-listenerhostnames:- "example.com"rules:- backendRefs:- name: web-svcnamespace: defaultport: 80sessionPersistence:type: CookiesessionName: "sticky-cookie"absoluteTimeout: 1hidleTimeout: 10mcookieConfig:lifetimeType: Session -
Apply the changes with
kubectl:nixkubectl apply -f http-route.yamlnixkubectl apply -f http-route.yamloutputtexthttproute.gateway.networking.k8s.io/session-persistence createdoutputtexthttproute.gateway.networking.k8s.io/session-persistence created
See also Jump to heading
- Refer to the Gateway API’s HTTPRoute documentation.