ingress重定向例子

子路径重定向

所有子路径匹配转发

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
name: whoami
namespace: default
spec:
rules:
- host: k8s-ingress-nbugs.nbugs.com
http:
paths:
- backend:
serviceName: whoami
servicePort: 80
path: /(.*)
pathType: ImplementationSpecific

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$1
name: whoami
namespace: default
spec:
rules:
- host: k8s-ingress-nbugs.nbugs.com
http:
paths:
- backend:
serviceName: whoami
servicePort: 80
path: /
pathType: ImplementationSpecific

访问http://k8s-ingress-nbugs.nbugs.com/awdseawdawda/awdawd/awdawd

所有都被重定向到/

image-20211109112035645

自定义路径转发

1
2
3
4
5
6
7
8
9
10
11
    nginx.ingress.kubernetes.io/rewrite-target: /abc/$1
spec:
rules:
- host: k8s-ingress-nbugs.nbugs.com
http:
paths:
- backend:
serviceName: whoami
servicePort: 80
path: /
pathType: ImplementationSpecific

访问http://k8s-ingress-nbugs.nbugs.com/1/2/3

image-20211109122522422

1
2
3
4
5
6
7
8
9
10
11
    nginx.ingress.kubernetes.io/rewrite-target: /abc/$1
spec:
rules:
- host: k8s-ingress-nbugs.nbugs.com
http:
paths:
- backend:
serviceName: whoami
servicePort: 80
path: /(.*)
pathType: ImplementationSpecific

访问http://k8s-ingress-nbugs.nbugs.com/1/2/3

image-20211109122651505

$路径匹配规则

1
2
3
4
5
6
7
nginx.ingress.kubernetes.io/rewrite-target: /abc/$1
http:
paths:
- backend:
serviceName: whoami
servicePort: 80
path: /(.*)/(.*)

访问

image-20211109123146463

image-20211109123157360

1
2
nginx.ingress.kubernetes.io/rewrite-target: /api/$2
path: /apiv2(/|$)(.*)

结果:

image-20211109144644112

image-20211109144700521

image-20211109144705928

1
2
3
4
5
nginx.ingress.kubernetes.io/configuration-snippet: rewrite /(.*)/(.*)$ /$2 break;
path: /

nginx.ingress.kubernetes.io/rewrite-target: /$2
path: /(.*)/(.*)$

结果: 只保留最后访问的文件名

image-20211109150555745

image-20211109150602777

image-20211109150611341

总结:

path中如果只有一个组

域名重定向

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
rewrite /(.*)$ /$1 break;
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: 'rewrite ^/li800/(.*)$ https://xxoo60.xxoo800.com/li800/$1 redirect;'
name: whoami
namespace: default
spec:
rules:
- host: k8s-ingress-nbugs.nbugs.com
http:
paths:
- backend:
serviceName: whoami
servicePort: 80
path: /
pathType: ImplementationSpecific

访问域名k8s-ingress-nbugs.nbugs.com/li800/abc

链接被重定向至https://xxoo60.xxoo800.com/li800/abc

参考:

https://blog.51cto.com/weifan/2451983

https://blog.csdn.net/lswzw/article/details/104496837

https://www.cnblogs.com/malukang/p/13534220.html