简体   繁体   English

如何使用 nginx 入口控制器拥有标头路由逻辑?

[英]How to have a header routing logic with nginx ingress-controller?

I'm trying to achieve a header routing ingress rule with nginx.我正在尝试使用 nginx 实现标头路由入口规则。 Why ?为什么 ? Because the same path should go to different backend based on headers .因为相同的路径应该根据headers转到不同的后端 Here what i've tried:这是我尝试过的:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: api-mutli-back
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      set $dataflag 0;

      if ( $http_content_type ~ "multipart\/form-data.*" ){
      set $dataflag 1;
      }

      if ( $dataflag = 1 ){
      set $service_name "backend-data";
      }

spec:
  rules:
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: backend-default
          servicePort: 80
        path: /api

But the logs of nginx output this error:但是nginx的日志输出这个错误:

unknown directive "set $service_name backend-data" in /tmp/nginx-cfg864446123:1237

which seems unlogic to me... If I check the configuration generated by nginx, each rule generate a location with something like this at the begining:这对我来说似乎不合逻辑......如果我检查nginx生成的配置,每个规则都会在开始时生成一个类似这样的位置:

[...]
       location ~* "^/api" {

            set $namespace      "my-namespace";
            set $ingress_name   "api-multi-back";
            set $service_name   "backend-default";
[...]

What am I doing wrong ?我究竟做错了什么 ? Isn't it possible to redefine service_name variable with annotation configuration-snippet ?是否可以使用注释configuration-snippet重新定义service_name变量? Is there any other method ?还有其他方法吗?

Edit: My error on nginx side was due to the lack of exact spaces between set $service_name and backend-data .编辑:我在 nginx 方面的错误是由于set $service_namebackend-data之间缺少确切的空格。 Then nginx generated correctly the configuration but it still not routing to another kubernetes service.然后 nginx 正确生成了配置,但它仍然没有路由到另一个 kubernetes 服务。

You got bitten by a YAML-ism:你被 YAML 主义咬了:

The indentation of your 2nd if block isn't the same as the indentation of the others, and thus YAML thinks you are starting a new key under annotations:您的第二个if块的缩进与其他块的缩进不同,因此 YAML 认为您正在annotations:下开始一个新键annotations:

You have你有

metadata:
  name: api-mutli-back
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      set $dataflag 0;

      if ( $http_content_type ~ "multipart\/form-data.*" ){
      set $dataflag 1;
      }

     if ( $dataflag = 1 ){
     set $service_name "backend-data"
     }

but you should have:但你应该有:

metadata:
  name: api-mutli-back
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      set $dataflag 0;

      if ( $http_content_type ~ "multipart\/form-data.*" ){
      set $dataflag 1;
      }

      if ( $dataflag = 1 ){
      set $service_name "backend-data"
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM