Search code examples
kubernetes-ingressamazon-eksnginx-ingress

Can i route host directly to a path in the backend?


I am using nginx-ingress.

Is it possible to route host to a path of the backend?

For example,

foo.example.com/ -> my-service:80/myapp/gui/ bar.example.com/ -> my-service:80/different/path/here

I tried this

spec:
  rules:
  - host: foo.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              name: http
            path: /myapp/gui/

Thought, it's throwing an error with unknown field.

$ k apply -f ingress.yaml error: error validating "ingress.yaml": error validating data: ValidationError(Ingress.spec.rules[0].http.paths[0].backend.service): unknown field "path" in io.k8s.api.networking.v1.IngressServiceBackend; if you choose to ignore these errors, turn validation off with --validate=false


Solution

  • It's can be done with two ingress config class and use ofnginx.ingress.kubernetes.io/rewrite-target annotation to route change the path :

        apiVersion: networking.k8s.io/v1
        kind: Ingress
        metadata:
          annotations:
            nginx.ingress.kubernetes.io/rewrite-target: /myapp/gui/$2
        spec:
          rules:
          - host: foo.example.com
            http:
              paths:
                - path: (/|$)(.*)
                  backend:
                    serviceName: my-service
                    servicePort: 80
    
    
        apiVersion: networking.k8s.io/v1
        kind: Ingress
        metadata:
          annotations:
            nginx.ingress.kubernetes.io/rewrite-target: /different/path/here/$2
        spec:
          rules:
          - host: bar.example.com
            http:
              paths:
                - path: (/|$)(.*)
                  backend:
                    serviceName: my-service
                    servicePort: 80
    
    

    The path will be "/myapp/gui/$2" where $2 will be replaced by your subpath.

    foo.example.com/ -> my-service:80/myapp/gui/ 
    foo.example.com/test -> my-service:80/myapp/gui/test
    bar.example.com/ -> my-service:80/different/path/here
    bar.example.com/test -> my-service:80/different/path/here/test