ingress rewrite domain www to non-www url

11/4/2019

I am trying to redirect my domain 'www.test.example.com' to test.example.com

in ingress i have added annotation

nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'www.test.wotnot.io' ) {
          rewrite ^/(.*)$ https://app.test.wotnot.io/$1 permanent;
      }

it's not working as expected.

For testing i have try this

nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($host = 'test.example.com' ) {
          rewrite ^/(.*)$ https://google.com/$1 permanent;
      }

which is working fine.

My site is working on test.example.com and ssl certificate.

Whole ingress

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    certmanager.k8s.io/cluster-issuer: wordpress-staging
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
    #nginx.ingress.kubernetes.io/configuration-snippet: |
      #if ($host = 'www.test.wotnot.io' ) {
        #  rewrite ^/(.*)$ https://test.example.io/$1 permanent;
      #}
  name: wordpress-staging-ingress
spec:
  rules:
  - host: test.example.io
    http:
      paths:
      - backend:
          serviceName: wordpress-site
          servicePort: 80
        path: /
  tls:
  - hosts:
    - test.example.io
    secretName: wordpress-staging
--
kubernetes
kubernetes-ingress
nginx-ingress

1 Answer

11/4/2019

Ingress has an annotation nginx.ingress.kubernetes.io/from-to-www-redirect: "true" which already handle this:

In some scenarios is required to redirect from www.domain.com to domain.com or vice versa. To enable this feature use the annotation nginx.ingress.kubernetes.io/from-to-www-redirect: "true"

Attention: For HTTPS to HTTPS redirects is mandatory the SSL Certificate defined in the Secret, located in the TLS section of Ingress, contains both FQDN in the common name of the certificate.

It's better that you use it instead of fighting/tweaking the configuration-snippet annotation.

-- Eduardo Baitello
Source: StackOverflow