Search code examples
nginxkuberneteskubernetes-ingress

How to capture subdomain in nginx ingress


I want to capture subdomain and rewrite URL with /subdomain, For example bhautik.bhau.tk rewrite to bhau.tk/bhautik.

I also https://github.com/google/re2/wiki/Syntax tried group syntax

Here is my nginx ingress config:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: subdomain
  namespace: subdomain
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    # nginx.ingress.kubernetes.io/rewrite-target: /$sub
    nginx.ingress.kubernetes.io/server-snippet: |
      set $prefix abcd;
      if ($host ~ ^(\w+).bhau\.tk$) {
        // TODO? 
      }
    nginx.ingress.kubernetes.io/rewrite-target: /$prefix/$uri
spec:
  rules:
  - host: "*.bhau.tk"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: subdomain
            port:
              number: 80

How do I capture subdomain from $host?


Solution

  • I believe you want a redirect instead of rewrite. Here is the server-snippet you need:

    nginx.ingress.kubernetes.io/server-snippet: |
      if ($host ~ ^(?<subdom>\w+)\.(?<basedom>bhau\.tk)$) {
        return 302 https://$basedom/$subdom/ ;
      }
    

    If you really want a rewrite where the URL that the user sees remains unchanged but instead the request will be routed to a subpath served by the same service:

    nginx.ingress.kubernetes.io/server-snippet: |
      if ($host ~ ^(?<subdom>\w+)\.(?<basedom>bhau\.tk)$) {
        rewrite ^/(.*)$ /$subdom/$1 ;
      }
    

    Remove the rewrite-target annotation that specifies $prefix. You don't need it.

    The ?<capturename> and $capturename pair is the trick you are looking for.