尝试以下操作,只需将 example.com 更改为您的域:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: reverse-redirect
annotations:
nginx.ingress.kubernetes.io/permanent-redirect: http://example.com
spec:
rules:
- http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: "somerandomname" # needs some name, doesn't need to exist
port:
number: 80
当向 nginx ingress 发送一个没有Host header 的请求时,它将默认使用没有指定host 字段的ingress(就像上面的例子一样)。此类请求将收到以下响应:
$ curl 123.123.123.123 -I
HTTP/1.1 301 Moved Permanently
Date: Wed, 28 Apr 2021 11:36:05 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
Location: http://example.com
收到此重定向的浏览器,将重定向到Location 标头中指定的域。
文档:
编辑:
由于您没有使用 nginx ingress,您可以尝试使用重定向应用程序。
这是我在 dockerhub 上找到的带有一些随机图像的部署,它通过重定向响应每个请求。我不想教你安全,但我觉得我至少应该提一下,你不应该使用来自互联网的随机容器图像,如果你是,你是在自己的责任上做。最好从源代码构建一个并推送到您自己的存储库。
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: redir
name: redir
spec:
replicas: 1
selector:
matchLabels:
app: redir
template:
metadata:
creationTimestamp: null
labels:
app: redir
spec:
containers:
- image: themill/docker-nginx-redirect-301
name: docker-nginx-redirect-301
env:
- name: REDIRECT_CODE
value: "302"
- name: REDIRECT_URL
value: https://example.com
上述部署的服务:
apiVersion: v1
kind: Service
metadata:
labels:
app: redir
name: redir
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: redir
status:
loadBalancer: {}
现在是入口部分:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: prueba-web-ingress
annotations:
networking.gke.io/managed-certificates: certificateexample
kubernetes.io/ingress.global-static-ip-name: test
kubernetes.io/ingress.allow-http: "false"
spec:
rules:
- http:
paths:
- path: /
backend:
serviceName: redir
servicePort: 80
- host: example.com
http:
paths:
- path: /
backend:
serviceName: prueba-web
servicePort: 80
注意这里同样适用:没有为 redir 服务设置 host 字段,尽管 prueba-web 服务设置了它的主机字段。