Using an NGINX Ingresss in Kubernetes, I can't see a way to forward my traffic from non-www to www, or to another domain etc on a per-host basis
I've tried looking in configmap docs but can't see what I need. Maybe it can go in the ingress itself?
I've also seen an example using annotations but this seems to be ingress-wide, so I couldn't have specific redirects per host
Indeed a redirect is possible with a simple annotation:
nginx.ingress.kubernetes.io/permanent-redirect: https://www.gothereinstead.com
nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
But as you mentioned, it's "Ingress" wide and not configurable per host, per domain or even per path. So you'll have to do it yourself through the ingress.kubernetes.io/configuration-snippet
annotation, which gives you a great deal of power thanks to regular expressions:
kind: Ingress
apiVersion: extensions/v1beta1
metadata:
name: self-made-redirect
annotations:
ingress.kubernetes.io/configuration-snippet: |
if ($host = 'blog.yourdomain.com') {
return 301 https://yournewblogurl.com;
}
if ($host ~ ^(.+)\.yourdomain\.com$) {
return 301 https://$1.anotherdomain.com$request_uri;
}
spec:
rules:
- host: ...
If you are not quite used to NGINX, you'll know more about what's possible in the snippet, particularly what is the $host
variable right in the NGINX documentation.
To redirect all traffic regardless of using HTTP or HTTPS from example.com and www.example.com to newdomain.example.com I ended up with the following solution.
In this example I'm also using cert-manager.io to request the certs for www.example.com and example.com.
The redirect is done using the annotation nginx.ingress.kubernetes.io/permanent-redirect
kind: Ingress
apiVersion: extensions/v1beta1
metadata:
name: redirect-example-to-newdomain
annotations:
kubernetes.io/ingress.class: "nginx"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/permanent-redirect: https://newdomain.example.com
spec:
tls:
- hosts:
- example.com
- www.example.com
secretName: example.com-tls
rules:
- host: example.com
- host: www.example.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With