Nginx中将正式环境流量copy一份到测试环境
当测试环境需要一些数据时,除了仿造一些数据外,更方便和更好的做法是,将来自正式环境的用户请求copy一份到测试环境。
依赖模块:lua-nginx-module,ngx_devel_kit, headers-more-nginx-module
以上模块在github上均可以找到,作者是国内nginx的著名开发者agentzh。
使用模块需要重新编译nginx,加上编译选项:–add-module=/path/to/your/module 。
下面是nginx配置:
>>cat copy_req.lua
local res1, res2, action
action = ngx.var.request_method
if action == “POST” then
arry = {method = ngx.HTTP_POST, body = request_body}
else
arry = {method = ngx.HTTP_GET}
end
if ngx.var.svr == “on” then
res1, res2 = ngx.location.capture_multi {
{ “/s1″ .. ngx.var.request_uri , arry},
{ “/test” .. ngx.var.request_uri , arry},
}
else
res1, res2 = ngx.location.capture_multi {
{ “/s1″ .. ngx.var.request_uri , arry},
}
end
if res1.status == ngx.HTTP_OK then
local header_list = {“Content-Length”, “Content-Type”, “Content-Encoding”, “Accept-Ranges”}
for _, i in ipairs(header_list) do
if res1.header[i] then
ngx.header[i] = res1.header[i]
end
end
ngx.say(res1.body)
else
ngx.status = ngx.HTTP_NOT_FOUND
end
>>cat nginx.conf
……..
location ~* ^/s1 {
log_subrequest on;
rewrite ^/s1(.*)$ $1 break;
proxy_pass http://s1;
access_log /opt/logs/nginx/youni/upstream.log;
}
location ~* ^/test {
log_subrequest on;
rewrite ^/test(.*)$ $1 break;
proxy_pass http://test;
access_log /opt/logs/nginx/youni/upstream.log;
}
location ~* ^/(.*)$ {
client_body_buffer_size 2m;
set $svr “on”; #开启或关闭copy功能
content_by_lua_file req_fenliu.lua;
}
upstream s1 {
server x.x.x.x;
}
upstream test {
server xx.xx.xx.xx;
}
其中nginx.conf内的http,server域没有给出,大家依照自己的配置即可。