ACCESS TO IT INTEL GRANTED

Rewrite and redirect rules with regex capture groups

TARGET_ENV: ingress-nginx 1.4+, Kubernetes 1.23+
[ TAGS: nginx, snippet, ingress, rewrite, regex, routing ]

This snippet uses the rewrite-target and use-regex annotations to perform path rewriting with capture groups. The controller translates the annotations into a location block containing a rewrite directive with the supplied regex and a proxy_pass to the backend. Capture groups from the path regex are substituted into the rewrite target, enabling versioned API gateways where /v1/users/123 becomes /users/123 upstream, or multi-tenant routing where /tenant-a/api is stripped before reaching the service.

In production this pattern is ubiquitous for API versioning, legacy path migration, and SaaS multi-tenancy. It is also used to map vanity URLs to internal service paths without changing client contracts. When combined with permanent-redirect, you can enforce canonical URLs and SEO-friendly 301s at the edge, reducing backend load.

Security note: regex-based rewrites must be anchored and validated; unanchored patterns can be exploited for path traversal or SSRF if the rewrite target is derived from user input. Always set use-regex only on the specific path that needs it, because enabling it globally changes matching semantics for all paths and can break exact-match routes. Performance is excellent — Nginx regex matching is compiled at config load — but overly complex regexes with catastrophic backtracking can cause CPU spikes. A common pitfall is that rewrite-target applies to all paths in the Ingress; use separate Ingress objects per rewrite rule to avoid unintended side effects, and remember that capture group syntax in Kubernetes YAML requires escaping dollar signs in some editors.

> System.Execute()

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-rewrite
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  ingressClassName: nginx
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /v[0-9]+/(.*)
        pathType: ImplementationSpecific
        backend:
          service:
            name: api-backend
            port:
              number: 8080
      - path: /legacy/(.*)
        pathType: ImplementationSpecific
        backend:
          service:
            name: legacy-backend
            port:
              number: 8080

> Architecture & Security Context

Verified for Valters IT Hub. When deploying this configuration in a production homelab or enterprise environment, ensure that you monitor system resources and implement strict access controls. Administrator privileges are required.


ID: VALTERSIT-E509DA045A75

← BACK_TO_VAULT → CVE_DATABASE