Home > Software engineering >  How to Redirect example.com to example.com/login by using NGINX Ingress Controller
How to Redirect example.com to example.com/login by using NGINX Ingress Controller

Time:10-10

{{- $root := . -}}
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: {{ include "ingress.name" . }}
  namespace: demo
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
    -   host: "*.{{ .Values.host }}"
        http:
          paths:
            {{- range $index, $service := .Values.deployments }}
            -   path: {{ $service.pathPrefix }}(/|$)(.*)
                backend:
                  serviceName: {{ $service.deploymentName }}
                  servicePort: 80
            {{- end  }}
---

This ingress configuration is successfully working.

Additionally it is required that when anyone hit URL: http://example.com, it should redirect http://example.com/login permanently, so how can i achieve it?

Thanks.

CodePudding user response:

You can add the annotation like

nginx.ingress.kubernetes.io/server-snippet: |
      location ~ / {
         rewrite / https://<example.com to use $host>/login permanent;
      }

if want to use the configuration snippet

nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'https://example.com/') {
        return 301 https://example.com/login;
      }

or

nginx.ingress.kubernetes.io/configuration-snippet: |
         rewrite / https://example.com/login permanent;

you can use the variables also if looking instead of using the fixed value.

$request_uri, $uri, $host are few of variables you can leverage.

  • Related