我在ingress.yaml中具有以下配置,该配置将具有/ us / default / demoservice / health或/ custom / demoservice / health的uri转发请求到后端demoservice。我想从uri中检索uri的第一部分(即上述示例中的default或custom),并将其作为自定义 header 传递给上游。
我已经使用自定义 header 部署了入口configmap
X-MyVariable-Path: ${request_uri}
但这会发送完整的请求uri。如何拆分?
- path: "/(.*?)/(demoservice.*)$"
backend:
serviceName: demoservice
servicePort: 80
最佳答案
我找到了解决方案,对其进行了测试,并且可以正常工作。
您需要做的就是向您的入口对象添加以下注释:
nginx.ingress.kubernetes.io/use-regex: "true"
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header X-MyVariable-Path $1;
$1
引用的是path:
字段中第一组正则表达式中捕获的内容。我已使用以下yaml复制了您的方案:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header X-MyVariable-Path $1;
nginx.ingress.kubernetes.io/use-regex: "true"
name: foo-bar-ingress
spec:
rules:
- http:
paths:
- backend:
serviceName: echo
servicePort: 80
path: /(.*?)/(demoservice.*)$
---
apiVersion: v1
kind: Service
metadata:
labels:
run: echo
name: echo
spec:
ports:
- port: 80
targetPort: 80
selector:
run: echo
---
apiVersion: v1
kind: Pod
metadata:
labels:
run: echo
name: echo
spec:
containers:
- image: mendhak/http-https-echo
imagePullPolicy: Always
name: echo
您可以使用curl进行测试:
curl -k https://<your_ip>/default/demoservice/healthz
输出:
{
"path": "/default/demoservice/healthz",
"headers": {
"host": "192.168.39.129",
"x-request-id": "dfcc67a80f5b02e6fe6c647c8bf8cdf0",
"x-real-ip": "192.168.39.1",
"x-forwarded-for": "192.168.39.1",
"x-forwarded-host": "192.168.39.129",
"x-forwarded-port": "443",
"x-forwarded-proto": "https",
"x-scheme": "https",
"x-myvariable-path": "default", # your variable here
"user-agent": "curl/7.52.1",
"accept": "*/*"
},
"method": "GET",
"body": "",
"fresh": false,
"hostname": "192.168.39.129",
"ip": "::ffff:172.17.0.4",
"ips": [],
"protocol": "http",
"query": {},
"subdomains": [],
"xhr": false,
"os": {
"hostname": "echo"
}
}
希望对您有帮助=)
关于kubernetes - 如何在Kubernetes入口 Controller 中将请求URI的部分作为自定义 header 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421113/