Nginx根據url引數轉發
阿新 • • 發佈:2022-03-22
原文: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; }