【发布时间】:2019-04-30 07:39:37
【问题描述】:
在 Kubernetes 中使用 NGINX 入口,我看不到将流量从非 www 转发到 www 或基于每个主机的另一个域等的方法
我尝试查看 configmap 文档,但看不到我需要什么。也许它可以进入入口本身?
我还看到了一个使用注释的示例,但这似乎是入口范围的,所以我无法为每个主机提供特定的重定向
【问题讨论】:
在 Kubernetes 中使用 NGINX 入口,我看不到将流量从非 www 转发到 www 或基于每个主机的另一个域等的方法
我尝试查看 configmap 文档,但看不到我需要什么。也许它可以进入入口本身?
我还看到了一个使用注释的示例,但这似乎是入口范围的,所以我无法为每个主机提供特定的重定向
【问题讨论】:
确实可以通过简单的注释进行重定向:
nginx.ingress.kubernetes.io/permanent-redirect: https://www.gothereinstead.comnginx.ingress.kubernetes.io/from-to-www-redirect: "true"但正如您所提到的,它是“入口”范围的,并且不能为每个主机、每个域甚至每个路径配置。因此,您必须自己通过 ingress.kubernetes.io/configuration-snippet 注释来完成,这要归功于正则表达式,它为您提供了强大的功能:
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: ...
如果你不太习惯 NGINX,你会知道更多关于 sn-p 中可能发生的事情,尤其是 the NGINX documentation 中的 $host 变量。
【讨论】:
无论使用 HTTP 或 HTTPS,将所有流量从 example.com 和 www.example.com 重定向到 newdomain.example.com,我最终得到了以下解决方案。
在此示例中,我还使用 cert-manager.io 来请求 www.example.com 和 example.com 的证书。
重定向是使用注解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
【讨论】:
我有注释 server-sn-p 的问题。更新证书时,进程崩溃。当我删除注释时,更新的证书是成功的。还有其他解决方案吗?例如,在单独的 pod 中创建重定向 301?
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
certmanager.k8s.io/cluster-issuer: letsencrypt-prod
ingress.kubernetes.io/ssl-redirect: "true"
meta.helm.sh/release-name: DOMAIN
meta.helm.sh/release-namespace: DOMAIN
nginx.ingress.kubernetes.io/configuration-snippet: |
location ~ ^/online-web {
return 301 /online;
}
if ($host = 'DOMAIN-alias.cz') {
return 301 https://DOMAIN.cz;
}
if ($host ~ ^(.+)\.DOMAIN-alias\.cz$) {
return 301 https://$1.DOMAIN.cz$request_uri;
}
if ($host = 'DOMAIN-alias-2.cz') {
return 301 https://DOMAIN.cz;
}
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
nginx.ingress.kubernetes.io/server-snippet: |
if ($host ~ "csas.woltair.cz") {
return 301 https://woltair.cz/zakaznik/doporuceni;
}
............
............
- host: csas.woltair.cz
http:
paths:
- backend:
service:
name: woltair-cz-fe
port:
number: 8080
path: /zakaznik/doporuceni
pathType: ImplementationSpecific
【讨论】: