首页  >  问答  >  正文

nginx conf 的设置问题

1

在 http {} 部分, 设置了

map $http_header_1 $route {default 10;}
map $http_header_2 $route {default 20;}
map $http_header_3 $route {default 30;}

请求的header设置为

curl -H "header_1:0" http://xxx.com/xxx

然后在 server {} 部分,

echo "$route";

打印结果始终为 30, 因为 第三个map指令覆盖了前面的值;

问题来了: 如何在map部分根据不同的header, 获得想要的值?

2

为解决问题1, 我想的办法为

map $http_header_1 $route1 {default 10;}
map $http_header_2 $route2 {default 20;}
map $http_header_3 $route3 {default 30;}

然后在 location {} 部分, 用

if ($http_header_1) {
echo "$route1";
}

去获得想要的值; 可耻的是, 这个 if 似乎没成功, 而且nginx不推荐使用if


那么, 哪位深藏功与名的同学, 帮忙解答一下?

PHP中文网PHP中文网2688 天前597

全部回复(2)我来回复

  • 阿神

    阿神2017-05-16 17:31:03

    好吧, 用if搞定了, 可是nginx不推荐使用if, 哪位同学有更好的方案?


    @冰纷 那位, 似乎回复您的文本不能使用md格式, 我在这里回复您一下:

    感谢. 不过您的答案, 没有回答我的问题.

    我的业务需求是:

    map $http_header_1 $route {
    default 110;
    a       111;
    b       112;
    c       113;
    }
    map $http_header_2 $route {
    default 210;
    a       211;
    b       212;
    c       213;
    }
    map $http_header_3 $route {
    default 310;
    a       311;
    b       312;
    c       313;
    }
    

    也即, request带有且只带有 $httpheader1,$httpheader2,$httpheader3 的其中一个, 并有相应的值为 a,b,c 的其中一个.

    nginx需要根据判断该头的key, 并根据key对应的value返回一个确认的 $route 值.

    业务例子:

    1. curl -H "header_php:a" http://biz.domain.com/ 最终$route为 111, 并 fastcgi_pass localhost:111
    2. curl -H "header_python:b" http://biz.domain.com/ 最终$route为 212, 并 fastcgi_pass localhost:212
    3. curl -H "header_ruby:c" http://biz.domain.com/ 最终$route为 313, 并 fastcgi_pass localhost:313

    然后

    1. php-1监听111, php-2监听112, php-3监听113
    2. python-1监听211, python-2监听212, python-3监听213
    3. ruby-1监听311, ruby-2监听312, ruby-3监听313

    最终一共有9个业务进程, 各自监听一个端口.

    不要问我为什么会有这种奇葩需求, 深藏功与名啊~~~


    所以, 您的答案, 不能满足我的兽欲啊

    回复
    0
  • 漂亮男人

    漂亮男人2017-05-16 17:31:03

    楼主需要明白几处: 1. map指令内的语句是默认必然执行1 of N的。

    map $http_header_1 $route {default 10;}
    map $http_header_2 $route {default 20;}
    map $http_header_3 $route {default 30;}
    

    就相当于

    传入$http_header_1任意值(即使为null),返回$route=10;
    传入$http_header_2任意值(即使为null),返回$route=20;
    传入$http_header_3任意值(即使为null),返回$route=30;
    

    所以,最终传出的$route为30;

    map是组建多个传入值与传出值映射关系的指令,这个传入值最好在传入到map前已经被定义、赋值了,不然就直接执行default。

    楼主可以试试

        map $http_user_agent $route{
           "Baiduspider" 1; #当$http_user_agent为Baiduspider,返回$route = 1
           "Googlebot" 2; #当$http_user_agent为Googlebot,返回$route = 2
           default 0; #否则,返回$route = 0
        }
    

    回复
    0
  • 取消回复