Search code examples
kuberneteskubernetes-ingress

How to get the k8s ingress wildcard in the host and put it on the url path


I use k8s to deploy my services. I hope when I access the ingress host foo.example.com and the ingress forward it to server:8000/proxy/foo. The subdomain foo is dynamic and can be changed to any word. The expected result is as below:

  • foo.example.com -> server:8000/proxy/foo
  • bar.example.com -> server:8000/proxy/bar
  • ......

I knew the ingress host could use wildcards and use ingress-nginx rewrite can rewrite the url path. I use the ingress-nginx controller. The ingress yaml file like as below:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /proxy/${wildcard}/$1 # Could I use the host wildcard here?
name: nginx-forward
spec:
  rules:
  - host: *.example.com # I want to get the subdomain wildcard
    http:
      paths:
      - backend:
        service:
          name: service
        port:
          number: 8080
      path: /(.*)
      pathType: Prefix
  tls: # update this attribute
  - hosts:
    - *.example.com 
    secretName: my-secret

How could I use k8s ingress or other things to get what I want? Thanks.


Solution

  • You can use server snippet to get the subdomain:

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      annotations:
        kubernetes.io/ingress.class: nginx
        nginx.ingress.kubernetes.io/server-snippet: |
          server_name     ~^(?<subdomain>\w+)\.example\.com$;
        nginx.ingress.kubernetes.io/rewrite-target: /proxy/$subdomain/$1 
    name: nginx-forward
    spec:
      rules:
      - http:
          paths:
          - backend:
            service:
              name: service
            port:
              number: 8080
          path: /(.*)
          pathType: Prefix