Nginx 在将请求转发到服务之前删除匹配后的前缀
我有一个基本urlNginx 在将请求转发到服务之前删除匹配后的前缀,nginx,kubernetes,nginx-ingress,Nginx,Kubernetes,Nginx Ingress,我有一个基本urlapi.example.com 因此,ingress nginx将获得对api.example.com的请求,它应该执行以下操作 转发api.example.com/customer至customer srv 它不工作,它将整个mtach转发给客户srv,即/customer/requested\u url apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-service ann
api.example.com
因此,ingress nginx
将获得对api.example.com
的请求,它应该执行以下操作
转发api.example.com/customer
至customer srv
它不工作,它将整个mtach转发给客户srv,即/customer/requested\u url
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-service
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/use-regex: "true"
spec:
rules:
- host: api.example.in
http:
paths:
- path: /customer/?(.*)
pathType: Prefix
backend:
service:
name: customer-srv
port:
number: 3000
我尝试使用重写注释,但也不起作用,但这是可行的,但这不是我想要实现的
paths:
- path: /?(.*)
pathType: Prefix
backend:
service:
name: customer-srv
port:
number: 3000
比如说,
api.example.com/customer
应转到http://localhost:3000
非http://localhost:3000/customer
以下是我使用的yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-service
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
rules:
- host: api.example.in
http:
paths:
- path: /customer/?(.*)
pathType: Prefix
backend:
service:
name: customer-srv
port:
number: 3000
对于测试目的,我创建了一个echo服务器:
kubectl run --image mendhak/http-https-echo customer
然后是服务:
kubectl expose po customer --name customer-srv --port 3000 --target-port 80
我检查了igress ip:
$ kubectl get ingress
NAME CLASS HOSTS ADDRESS PORTS AGE
ingress-service <none> api.example.in 192.168.39.254 80 3m43s
请注意,echo服务器回显了它接收到的路径,并且在它接收到从/customer/asd
到/asd
重写的路径时,它显示了这个执行路径(/asd)
正如您所看到的,这确实有效。“我尝试过使用重写注释,但不起作用”-它有什么问题?什么不起作用?我尝试将api.example.com/customer重写为
/
现在,在重新匹配所有路由后,这将转到默认处理程序,而这将转到客户。在使用重写目标:/$1
后,使用路径:/customer/?(.*)
,您看到了什么与您期望看到的相比?因为在imo中,当您使用像这样的重写目标时,它应该可以工作。但是,当您正在重写路径而应用程序不知道这一点时,可能会出现一些问题。但这完全取决于实际的应用程序,我无法在不了解应用程序工作原理的情况下帮助您。许多web应用程序允许您设置所谓的基本路径
或根路径
,从而为网站生成的所有路径添加前缀。e、 g.当你在/上请求一个网站时,你会得到带有图像路径、js脚本等的html数据。想象一下你将某个路径/网站重写为/时,网站会看到/并向你提供有关图像的html。让我们假设html看起来像:
。这很有效@Matt谢谢。
curl 192.168.39.254/customer/asd -H "Host: api.example.in"
{
"path": "/asd",
"headers": {
"host": "api.example.in",
...
}