Kubernetes ingress domain redirect

ghz 7months ago ⋅ 38 views

i want to redirect domain in nginx ingress kubernete.

https://test.example.io/preview/qLxiVcDGxCaQ134650121853FTg4

if in url preview comes change domain redirect

https://test.app.example.io/preview/qLxiVcDGxCaQ134650121853FTg4

what i was trying

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    certmanager.k8s.io/cluster-issuer: staging
    nginx.ingress.kubernetes.io/rewrite-target: /
    kubernetes.io/ingress.class: nginx
  name: staging-ingress
spec:
  rules:
  - host: test.example.io
    http:
      paths:
      - path: /
        backend:
          serviceName: service-1
          servicePort: 80
      - path: /preview/*
        backend:
          url: 
          serviceName: service-2
          servicePort: 80
  tls:
  - hosts:
    - test.example.io
    secretName: staging

for simple nginx block is like

location ~ /preview
    {
      rewrite /preview https://test.app.example.com$uri permanent;
    }

Answers

To achieve the desired redirection in the Nginx Ingress controller in Kubernetes, you can use annotations to configure custom Nginx directives. In your case, you want to redirect requests from test.example.io/preview/* to https://test.app.example.io/preview/*.

Here's how you can modify your Ingress resource YAML to achieve this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/cluster-issuer: staging
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($request_uri ~* "^/preview/(.*)$") {
        return 301 https://test.app.example.io/preview/$1;
      }
  name: staging-ingress
spec:
  rules:
  - host: test.example.io
    http:
      paths:
      - path: /
        backend:
          serviceName: service-1
          servicePort: 80
  tls:
  - hosts:
    - test.example.io
    secretName: staging

Explanation:

  • The nginx.ingress.kubernetes.io/configuration-snippet annotation allows you to add custom Nginx configuration snippets.
  • The if statement checks if the request URI matches the pattern /preview/*.
  • If the condition is true, it performs a permanent redirect (HTTP 301) to https://test.app.example.io/preview/* using the captured group $1.

Make sure to replace serviceName and servicePort with the appropriate values for your services. Also, ensure that the necessary Nginx Ingress Controller is deployed in your Kubernetes cluster, and it has support for these annotations.

After applying this configuration, requests to test.example.io/preview/* should be redirected to https://test.app.example.io/preview/*.