nginx通过判断参数值最后两位转发到不同后端服务

 

方案1 使用全局变量$args

location /test {
default_type text/html;

# 获取 user_id 参数值
if ($args ~* "user_id=(\d+)") {
set $user_id $1;
}

# 对最后两位数进行正则匹配
if ($user_id ~* "(\d{2})$") {
  set $last_two_digits $1;
}

# 根据条件转发到后端服务
if ($last_two_digits ~* "^([0-3][0-9])$" ) {
  echo "user_id_a=$last_two_digits";
}
  echo "user_id_b=$last_two_digits";

}

方案2-1 使用全局变量$arg
location /test2 {
default_type text/html;

#获取user_id最后两位数
if ($arg_user_id ~* "(\d{2})$") {
  set $user_id_last_two $arg_user_id;
}

# 根据条件转发到后端服务
if ($user_id_last_two ~* "([0-3][0-9])$") {
  echo "user_id_a=$user_id_last_two";
}
  echo "user_id_b=$user_id_last_two";
}

方案2-2

location /test2 {
default_type text/html;

#获取user_id参数值
if ($arg_user_id ~* "(\d+)$") {
  set $user_id_last_two $arg_user_id;
}

# 根据条件转发到后端服务
if ($user_id_last_two ~* "([0-3][0-9])$") {
  echo "user_id_a=$user_id_last_two";
}
  echo "user_id_b=$user_id_last_two";
}

 

 

 
posted @ 2023-05-17 11:20  GaoYanbing  阅读(478)  评论(0编辑  收藏  举报