<p>I've the below configuration in ingress.yaml which forwards the requests with uris like /default/demoservice/health or /custom/demoservice/health to backend demoservice. I would want to retrieve the first part of uri (i.e default or custom in the example above)from the uri and pass as custom header to upstream.</p>

<p>I've deployed the ingress configmap with custom header </p>

<pre><code>X-MyVariable-Path: ${request_uri} 
</code></pre>

<p>but this sends the full request uri. How can I split?</p>

<pre><code>- path: "/(.*?)/(demoservice.*)$"
  backend:
    serviceName: demoservice
    servicePort: 80
</code></pre>

<p>I have found a solution, tested it and it works.<br>
All you need is to add following annotations to your ingress object :</p>

<pre><code>nginx.ingress.kubernetes.io/use-regex: "true"
nginx.ingress.kubernetes.io/configuration-snippet: |  
proxy_set_header X-MyVariable-Path $1;  
</code></pre>

<p>Where <code>$1</code> is referencing whatever is captured in first group of regexp expression in <code>path:</code> field.</p>

<p>I've reproduced your scenario using the following yaml:</p>

<pre><code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header  X-MyVariable-Path  $1;
    nginx.ingress.kubernetes.io/use-regex: "true"
  name: foo-bar-ingress
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: echo
          servicePort: 80
        path: /(.*?)/(demoservice.*)$
---
apiVersion: v1
kind: Service
metadata:
  labels:
    run: echo
  name: echo
spec:
  ports:
  - port: 80
    targetPort: 80
  selector:
    run: echo
---
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: echo
  name: echo
spec:
  containers:
  - image: mendhak/http-https-echo
    imagePullPolicy: Always
    name: echo
</code></pre>

<p>You can test using curl:</p>

<p><code>curl -k https://&lt;your_ip&gt;/default/demoservice/healthz</code></p>

<p>Output:</p>

<pre><code> {
  "path": "/default/demoservice/healthz",
  "headers": {
    "host": "192.168.39.129",
    "x-request-id": "dfcc67a80f5b02e6fe6c647c8bf8cdf0",
    "x-real-ip": "192.168.39.1",
    "x-forwarded-for": "192.168.39.1",
    "x-forwarded-host": "192.168.39.129",
    "x-forwarded-port": "443",
    "x-forwarded-proto": "https",
    "x-scheme": "https",
    "x-myvariable-path": "default", # your variable here
    "user-agent": "curl/7.52.1",
    "accept": "*/*"
  },
  "method": "GET",
  "body": "",
  "fresh": false,
  "hostname": "192.168.39.129",
  "ip": "::ffff:172.17.0.4",
  "ips": [],
  "protocol": "http",
  "query": {},
  "subdomains": [],
  "xhr": false,
  "os": {
    "hostname": "echo"
  }
}
</code></pre>

<p>I hope it helps =)</p>
