nginx入口如何根据http头部重定向URL? [英] How to redirect URL based on http header in nginx ingress?
本文介绍了nginx入口如何根据http头部重定向URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
推荐答案
当前Ingress
的资源定义不支持基于标头的路由。
我找到了一种解决办法根据请求的标头路由请求(我已经包含了以下步骤),带有以下注释:
nginx.ingress.kubernetes.io/configuration-snippet: |
if ($http_LocationHeader = "PL") { proxy_pass http://goodbye-service.default.svc.cluster.local:5678; }
其他可能的解决方案/变通办法:
- 使用
Traefik
:Docs.traefik.io: Routing: Routers - 使用
Ambassador
:Getambassador.io: Docs: Using: Headers - 使用
Istio
:Istio.io: Traffic management: Request routing - 将流量从
nginx-ingress
路由到nginx实例/部署/后台启动,包含包头路由逻辑:Stackoverflow.com:如何拥有nginx入口控制器的包头路由逻辑? (答案下的最后一个评论)
对于解决办法:
假设(出于示例目的):
- 共有2个部署:
hello
、goodbye
- 这两个名称都与其服务相关联:
hello-service
,goodbye-service
Ingress
资源将以hello
应始终应答的方式进行配置,但是添加configuration-snippet
后,通信将重定向到goodbye
。
此部署的响应:
| hello | goodbye |
|----------------|----------------|
| Hello, world! | Hello, world! |
| Version: 2.0.0 | Version: 1.0.0 | # notice the version
附加服务的hello
部署示例:
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello
spec:
selector:
matchLabels:
app: hello
replicas: 1
template:
metadata:
labels:
app: hello
spec:
containers:
- name: hello
image: "gcr.io/google-samples/hello-app:2.0"
env:
- name: "PORT"
value: "50001"
---
apiVersion: v1
kind: Service
metadata:
name: hello-service
spec:
selector:
app: hello
ports:
- name: hello-port
port: 5678 # IMPORTANT
targetPort: 50001
type: NodePort
若要获得goodbye
部署,请对goodbye
使用替身hello
,并将映像版本更改为1.0
。
通过标头重新路由请求的入口定义如下所示:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: hello-ingress
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/configuration-snippet: |
if ($http_LocationHeader = "PL") { proxy_pass http://goodbye-service.default.svc.cluster.local:5678; }
spec:
rules:
- host:
http:
paths:
- path: /
backend:
serviceName: hello-service
servicePort: hello-port
默认情况下,不带configuration-snippet
的此入口定义将始终将流量路由到hello-service
,然后路由到hello
Pod。通过添加: nginx.ingress.kubernetes.io/configuration-snippet: |
if ($http_LocationHeader = "PL") { proxy_pass http://goodbye-service.default.svc.cluster.local:5678; }
它将检查名为LocationHeader
的标头是否存在,以及它是否与PL
匹配。如果是,它将按其DNS名称将请求发送到goodbye-service
。
重点关注:
http://goodbye-service.default.svc.cluster.local:5678
http://service_name.namespace.svc.cluster.local:port
(不带值的DNS名称)
应用此Ingress
资源后,您应该可以使用LocationHeader=PL
(例如Postman)发送请求并获得响应:
Hello, world!
Version: 1.0.0
Hostname: goodbye-5758448754-wr64c
当我尝试使用
map
指令时,收到以下消息:
nginx: [emerg] "map" directive is not allowed here in /tmp/nginx-OMMITED
这篇关于nginx入口如何根据http头部重定向URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文