介绍小需求
根据不同的请求参数转发到不同的服务
应用场景
- 可以更具用户Id进行Hash到不同的服务器上;
- 可以做nginx缓存,例如:商品详情页面,更具商品Id哈希取模请求转发到不同的nginx上;
- 更具请求中添加的参数区分环境,进行恢复发布(比如:正式环境、开发环境、预生产环境、演示环境、测试环境...);
具体需求,同一个请求不同参数转发到不同的服务上
1、配置nginx
server {
listen 80;
server_name localhost;
access_log /opt/lua/host.access.log;
charset utf-8;
location /a {
default_type text/html;
lua_code_cache on;
rewrite_by_lua_file /opt/lua/1.lua;
}
location @b {
# 这里可以做请求转发到相应的服务上
default_type text/html;
lua_code_cache on;
content_by_lua_block {
ngx.say("<p>b</p>")
}
}
location @c {
# 这里可以做请求转发到相应的服务上
default_type text/html;
lua_code_cache on;
content_by_lua_block {
ngx.say("<p>c</p>")
}
}
}
1.lua脚本文件
local request_method = ngx.var.request_method
local args = nil
local param= nil
if "GET" == request_method then
args = ngx.req.get_uri_args()
elseif "POST" == request_method then
ngx.req.read_body()
args = ngx.req.get_post_args()
end
param = args["a"]
if "1" == param then
ngx.exec("@b")
elseif "2" == param then
ngx.exec("@c")
end