Skip to content

One Practice

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: gateway-routes
  namespace: default
spec:
  parentRefs:
    - name: wildcard-gateway
  hostnames:
    - gateway.io
  rules:

  # POST /user -> /users
  - matches:
      - path:
          type: Exact
          value: /user
        method: POST
        headers:
          - type: RegularExpression
            name: x-api-key
            value: "abc123"
    # filters:
    #   - type: URLRewrite
    #     urlRewrite:
    #       path:
    #         type: ReplaceFullPath
    #         replaceFullPath: /users
    backendRefs:
      - name: backend-service
        port: 80

  # GET /api/v1/users -> /users
  - matches:
      - path:
          type: PathPrefix
          value: /api/v1/users
    filters:
      - type: URLRewrite
        urlRewrite:
          path:
            type: ReplacePrefixMatch
            replacePrefixMatch: /users
    backendRefs:
      - name: backend-service
        port: 80

  # GET /api/v1/posts -> /posts
  - matches:
      - path:
          type: PathPrefix
          value: /api/v1/posts
    filters:
      - type: URLRewrite
        urlRewrite:
          path:
            type: ReplacePrefixMatch
            replacePrefixMatch: /posts
    backendRefs:
      - name: backend-service
        port: 80

  # /api/v1/catalog -> redirect to /api/v1/posts
  - matches:
      - path:
          type: Exact
          value: /api/v1/catalog
    filters:
      - type: RequestRedirect
        requestRedirect:
          path:
            type: ReplaceFullPath
            replaceFullPath: /api/v1/posts
          statusCode: 302

  # /google -> https://google.com/google
  - matches:
      - path:
          type: Exact
          value: /google
    filters:
      - type: RequestRedirect
        requestRedirect:
          scheme: https
          hostname: google.com
          statusCode: 302
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: wildcard-gateway
  namespace: default
spec:
  gatewayClassName: traefik
  listeners:
    - name: http
      protocol: HTTP
      port: 8000
      hostname: gateway.io
      allowedRoutes:
        namespaces:
          from: Same

    - name: https
      protocol: HTTPS
      port: 8443
      hostname: gateway.io
      tls:
        mode: Terminate
        certificateRefs:
          - kind: Secret
            name: gatewayio-cert
      allowedRoutes:
        namespaces:
          from: Same

Released under the MIT License.