nginx入口如何根据http头部重定向URL? [英] How to redirect URL based on http header in nginx ingress?

查看:12
本文介绍了nginx入口如何根据http头部重定向URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的请求通过Cloudflare进行代理,它根据IP地址在http报头中设置指示国家的报头。我想在Nginx入口控制器中根据这个头部重定向具有特定路径的请求。我该怎么做?

推荐答案

当前Ingress的资源定义不支持基于标头的路由。

我找到了一种解决办法根据请求的标头路由请求(我已经包含了以下步骤),带有以下注释:

    nginx.ingress.kubernetes.io/configuration-snippet: |
      if ($http_LocationHeader = "PL") { proxy_pass http://goodbye-service.default.svc.cluster.local:5678; }

其他可能的解决方案/变通办法:


对于解决办法

假设(出于示例目的):

  • 共有2个部署:hellogoodbye
  • 这两个名称都与其服务相关联:hello-servicegoodbye-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,然后路由到helloPod。通过添加:

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆