nginx根据url参数做转发
个人学习笔记,谢绝转载!!!
原文:https://www.cnblogs.com/wshenjin/p/13071392.html
线上一个需求,需要根据url参数的特定值做固定的转发处理。
例如 http://api.example.com/?boole=1234&ment=abcd&plat=mix_a&dupl=1234
plat=mix_[a|b|c|d]时,转发到http://api-bgp.example.com
location / {
proxy_redirect off;
proxy_set_header Host api-bgp.example.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if ( $query_string ~ "\bplat=mix_(a|b|c|d)\b" ){
proxy_pass $scheme://1.1.1.1:$server_port;
}
index index.php index.html index.htm;
}
另外一个需求,根据url参数的内容重写
http://api.example.com/ooo/xxx/index.php?version=1s1234&boole=1234&ment=abcd ---> http://api.example.com/ooo/xxx/rule.php?version=1s1234&boole=1234&ment=abcd
version=1sxxxx是1s后面跟上时间戳,例如:version=1s1598521028
location = /ooo/xxx/index.php {
if ( $query_string ~ "\bversion=1s(\d+)\b" ) {
rewrite /ooo/xxx/index.php /ooo/xxx/rule.php last;
}
include fcgi.conf;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
expires off;
}
另外一个需求,根据url参数返回不同的文件
http://api.example.com/ooo/xxx/xxx.dat?game=ggg&plat=ppp
要求:请求*.dat文件,参数game、plat必须存在,允许参数值为空,再参数值拼接出实际响应文件名,按xxx_${game}_${plat}.dat ==》xxx_${game}.dat ==》xxx.dat的顺序查到,存在就返回:
location ~ /ooo/xxx/.*\.dat$ {
set $dat "";
set $game "";
set $plat "";
if ( $uri ~ "/ooo/xxx/(.*)\.dat$"){
set $dat $1;
}
#取反匹配,要求game= plat=两个参数必须存在
if ( $query_string !~ "(\bgame=.*&plat=.*)|(\bplat=.*&game=.*)" ){
return 404;
}
if ( $query_string ~ "\bgame=(\w+)\b" ){
set $game $1;
}
if ( $query_string ~ "\bplat=(\w+)\b" ){
set $plat $1;
}
##参数拼接出文件名,xxx_{game}_{plat}.dat ==》xxx_{game}.dat ==》xxx.dat的顺序查到,存在就返回
if ( -f "/data/web/t/ooo/xxx/${dat}_${game}_${plat}.dat" ) {
rewrite /ooo/xxx/(.*) /ooo/xxx/${dat}_${game}_${plat}.dat break;
}
if ( -f "/data/web/t/ooo/xxx/${dat}_${game}.dat" ) {
rewrite /ooo/xxx/(.*) /ooo/xxx/${dat}_${game}.dat break;
}
rewrite /ooo/xxx/(.*) /ooo/xxx/${dat}.dat break;
}