Redirecting www to Non-www with Kubernetes Nginx Ingress
At Etéreo, we want www.etereo.io to be redirected to etereo.io for SEO reasons. There are multiple ways to achieve this, but since our website runs on a Kubernetes cluster with Nginx Ingress, we opted for the approach explained below.
Configuration
Redirecting domain.com to www.domain.com (or vice versa) using Kubernetes Nginx Ingress can be easily achieved with a specific annotation.
Steps:
Enable redirection using the annotation:
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"Define only the rules related to
www.domain.comin yourIngressresources:host: www.domain.com http: paths: - backend: serviceName: <your_service> servicePort: <your_service_port> path: <your_service_path>
This configuration ensures that Nginx returns a 308 HTTP Status Code (Permanent Redirect) on every request made to domain.com.
There is only one annotation for redirecting from and to www. This means:
- The configuration works only if
Ingressrules are defined for eitherwww.domain.comordomain.com. - If
Ingressrules exist for bothwww.domain.comanddomain.com, the redirect will not take effect.
HTTPS Redirection: If you want to redirect using HTTPS, you need a valid certificate for both domain.com and www.domain.com.
Example Configuration
Full Example with Service and Ingress Resources
kind: Service
apiVersion: v1
metadata:
name: my-website
namespace: my-website-namespace
spec:
selector:
name: my-website
ports:
- name: http
port: 80
targetPort: 80
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
nginx.ingress.kubernetes.io/rewrite-target: /
name: my-website
namespace: my-website-namespace
spec:
rules:
- host: www.domain.com
http:
paths:
- backend:
serviceName: my-website
servicePort: 80
path: /
Notes
To redirect from www to non-www, follow the same setup but define Ingress rules only for your host without www (domain.com).