Host rewrites
Replace the host header value before forwarding a request to a backend service.
For more information, see the Kubernetes Gateway API documentation.
Before you begin
-
Follow the Get started guide to install K8sGateway, set up a gateway resource, and deploy the httpbin sample app.
-
Get the external address of the gateway and save it in an environment variable.
export INGRESS_GW_ADDRESS=$(kubectl get svc -n gloo-system gloo-proxy-http -o jsonpath="{.status.loadBalancer.ingress[0]['hostname','ip']}") echo $INGRESS_GW_ADDRESS
kubectl port-forward deployment/gloo-proxy-http -n gloo-system 8080:8080
Rewrite hosts
Path rewrites use the HTTP path modifier to rewrite path prefixes.
-
Create a RouteOption resource to define your rewrite rules. In the following example the host request header is rewritten to the
www.example.com
host.kubectl apply -n httpbin -f- <<EOF apiVersion: gateway.solo.io/v1 kind: RouteOption metadata: name: rewrite namespace: httpbin spec: options: hostRewrite: 'www.example.com' EOF
-
Create an HTTPRoute resource for the httpbin app that references the RouteOption resource that you created. In this example, all incoming requests on the
rewrite.example
domain are rewritten to thewww.example.com
host as defined in the referenced RouteOption resource.kubectl apply -f- <<EOF apiVersion: gateway.networking.k8s.io/v1beta1 kind: HTTPRoute metadata: name: httpbin-rewrite namespace: httpbin spec: parentRefs: - name: http namespace: gloo-system hostnames: - rewrite.example rules: - filters: - type: ExtensionRef extensionRef: group: gateway.solo.io kind: RouteOption name: rewrite backendRefs: - name: httpbin port: 8000 EOF
-
Send a request to the httpbin app on the
rewrite.example
domain. Verify that you get back a 200 HTTP response code and that you see theHost: www.example.com
header in your response.ℹ️The following request returns a 200 HTTP response code, because you set up an HTTPRoute for the httpbin app on thewww.example.com
domain as part of the Getting started guide. If you chose a different domain for your example, make sure that you have an HTTPRoute that can be reached under the host you want to rewrite to.curl -vik http://$INGRESS_GW_ADDRESS:8080/headers -H "host: rewrite.example:8080"
curl -vik localhost:8080/headers -H "host: rewrite.example"
Example output:
... { "headers": { "Accept": [ "*/*" ], "Host": [ "www.example.com" ], "User-Agent": [ "curl/7.77.0" ], "X-Envoy-Expected-Rq-Timeout-Ms": [ "15000" ], "X-Forwarded-Proto": [ "http" ], "X-Request-Id": [ "ffc55a3e-60ae-4c90-9a5c-62c8a1ba1076" ] } }
-
Optional: Clean up the resources that you created.
kubectl delete routeoption rewrite -n httpbin kubectl delete httproute httpbin-rewrite -n httpbin