[nginx] 将请求指定到指定后端服务器
|
看似简单的需求,弄了半天弄不出来,本来想直接用 args 匹配到关键字然后提取出来,转发到后端,但是 nginx 直接把 request_ur[http://www.ceshi.com?server_name=server1]都参数都丢到后端了,导致后端没办法处理 server_name, 想到的是用 lua 脚本处理整个 $uri,把 server_name 这个参数去掉但是始终弄不出来,有空继续搞。
nginx 配置
upstream jweb { server server1:8009; server server2:8009; } server { location ~* (\/$)|\.(do|json|jsx|tile|resource|file|htm|checkcode|s)$ { ajp_keep_conn on; if ( $request_uri = "/" ) { rewrite "/" $uri/index.htm break; } if ( $http_server_name != "" ) { ajp_pass $http_server_name:8009; } ajp_pass jweb; index index.htm; } }
测试:
curl -H "server_name: server1" http://www.test.com/index.htm 可以在access.log里面看到到server1的服务器上了
用 postman 也可以
用 modify header 插件
lua 脚本 [未成功]:
-- @Author: richard -- @Date: 2017-08-11 13:01:31 -- @Last Modified by: richard -- @Last Modified time: 2017-08-11 14:40:58 function set_request_uri() local request_uri = ngx.var.request_uri; local question_pos, _ = string.find(request_uri, '?') local target = "" if question_pos>0 then local uri = string.sub(request_uri, 1, question_pos-1) local args = ngx.decode_args(string.sub(request_uri, question_pos+1)) if args.server_name then target = args.server_name if target == nil then target = "_" end args.remove(args,server_name) return uri .. '?' .. ngx.encode_args(args), target else return request_uri, _ end else return request_uri, _ end end return set_request_uri();