Custom redirect status codes
Create custom HTTP redirect status codes.
To customize HTTP redirect status codes, you can add the kgateway.dev/http-redirect-status-code annotation to an HTTPRoute. This annotation overrides any status codes that are defined in the RequestRedirect filter on the HTTPRoute. For example, in the Kubernetes Gateway API version 1.4.0, where you can set an HTTP redirect status code only to 301 or 302, this annotation is useful for allowing a status code other than one of those two.
For more information, see the Kubernetes Gateway API documentation.
Before you begin
-
Follow the Get started guide to install kgateway.
-
Follow the Sample app guide to create a gateway proxy with an HTTP listener 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 kgateway-system http -o jsonpath="{.status.loadBalancer.ingress[0]['hostname','ip']}") echo $INGRESS_GW_ADDRESSkubectl port-forward deployment/http -n kgateway-system 8080:8080
Set custom HTTP redirect status codes
-
Create an HTTPRoute that redirects the
/getand/posthttpbin paths to the/anythingpath with a 302 HTTP status code. To override the path-specific redirect code with a 307 HTTP response code, you add thekgateway.dev/http-redirect-status-codeannotation.kubectl apply -f- <<EOF apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: httpbin-redirect namespace: httpbin annotations: kgateway.dev/http-redirect-status-code: "307" spec: parentRefs: - name: http namespace: kgateway-system hostnames: - redirect.example rules: - matches: - path: type: PathPrefix value: /get filters: - type: RequestRedirect requestRedirect: path: type: ReplacePrefixMatch replacePrefixMatch: /anything statusCode: 302 - matches: - path: type: PathPrefix value: /post filters: - type: RequestRedirect requestRedirect: path: type: ReplacePrefixMatch replacePrefixMatch: /anything statusCode: 302 EOF -
Send an HTTP request to the httpbin app on the
redirect.exampledomain. Verify that you get back a 307 HTTP response code and that your request path is rewritten to the/anythingpath.curl -vik http://$INGRESS_GW_ADDRESS:8080/get -H "host: redirect.example"curl -vi localhost:8080/get -H "host: redirect.example"Example output:
* Request completely sent off < HTTP/1.1 307 Temporary Redirect HTTP/1.1 307 Temporary Redirect < location: http://redirect.example/anything location: http://redirect.example/anything < content-length: 0 content-length: 0
Cleanup
You can remove the resources that you created in this guide.Remove the HTTPRoute.
kubectl delete httproute httpbin-redirect -n httpbin