<p>I want to capture <code>subdomain</code> and rewrite URL with <code>/subdomain</code>, For example <code>bhautik.bhau.tk</code> rewrite to <code>bhau.tk/bhautik</code>.</p>
<p>I also <a href="https://github.com/google/re2/wiki/Syntax" rel="nofollow noreferrer">https://github.com/google/re2/wiki/Syntax</a> tried group syntax</p>
<p>Here is my <code>nginx</code> ingress config:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: subdomain
  namespace: subdomain
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: &quot;true&quot;
    # 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: &quot;*.bhau.tk&quot;
    http:
      paths:
      - pathType: Prefix
        path: &quot;/&quot;
        backend:
          service:
            name: subdomain
            port:
              number: 80
</code></pre>
<p>How do I capture subdomain from $host?</p>

Bhautik Chudasama
<p>I believe you want a redirect instead of rewrite. Here is the <code>server-snippet</code> you need:</p>
<pre><code>nginx.ingress.kubernetes.io/server-snippet: |
  if ($host ~ ^(?&lt;subdom&gt;\w+)\.(?&lt;basedom&gt;bhau\.tk)$) {
    return 302 https://$basedom/$subdom/ ;
  }
</code></pre>
<p>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:</p>
<pre><code>nginx.ingress.kubernetes.io/server-snippet: |
  if ($host ~ ^(?&lt;subdom&gt;\w+)\.(?&lt;basedom&gt;bhau\.tk)$) {
    rewrite ^/(.*)$ /$subdom/$1 ;
  }
</code></pre>
<p>Remove the <code>rewrite-target</code> annotation that specifies <code>$prefix</code>. You don't need it.</p>
<p>The <code>?&lt;capturename&gt;</code> and <code>$capturename</code> pair is the trick you are looking for.</p>
