Nginx做流量转发通过location创建不同规则进而可以将流量转发至不同的后端服务(location匹配规则不再赘述),本文所展示的两条location规则为在生产环境中用到的比较特殊的匹配案例,供大家参考。
场景一:
出网ip为固定ip并且ua为pc端的代理到服务A,不符合此规则的代理到服务B
location = /some/ {
set $new '0';
if ($remote_addr ~* "192.168.6.11|192.168.6.12") {
set $new '1';
}
if ($ua_device != 'is_mobile') { ###is_mobile为自定义变量,可参考nginx map
set $new "${new}2";
}
if ($new = '12') {
proxy_pass http://service A;
}
proxy_pass http://service B;
}
场景二
匹配文章id大于600000000的代理到服务A,其余的代理到服务B
location ~* ^/topics/(\d+) {
set $id $1;
set $new '0';
if ($id ~* "([6-9]{1,})([0-9]{8,})"){ ##其他取值范围可随意修改
set $new '1';
}
if ($new = '1'){
proxy_pass http://service A;
}
proxy_pass http://service B;
}
因篇幅问题不能全部显示,请点此查看更多更全内容