Nginxn ngx http mirror module实现流量镜像
来自Linux78|wiki
目录
ngx_http_mirror_module模块特性
nginx 1.13.4及后续版本内置ngx_http_mirror_module模块,提供流量镜像(复制)的功能。
支持流量放大,做法为:配置多份相同镜像。
相比tcp-copy的优势:无需录制流量,实时可用;配置相当简单。
源站请求,直接原路返回;正常配置下,mirror请求不影响源站请求及响应,源站nginx-server将流量复制到mirror站后,两者不再有任何交集。
Syntax: mirror uri | off; Default: mirror off; Context: http, server, location Sets the URI to which an original request will be mirrored. Several mirrors can be specified on the same level. Syntax: mirror_request_body on | off; Default: mirror_request_body on; Context: http, server, location
配置示例
location / {
mirror /mirror;
mirror_request_body off;# Indicates whether the client request body is mirrored. default value is on.
proxy_pass http://backend;
}
location /mirror {
internal;
proxy_pass http://test_backend$request_uri
}
original配置
location /指定了源uri为/ mirror /mirror指定镜像uri为/mirror mirror_request_body off | on 指定是否镜像请求body部分,此选项与proxy_request_buffering、fastcgi_request_buffering、scgi_request_buffering和 uwsgi_request_buffering冲突,一旦开启mirror_request_body为on,则请求自动缓存; proxy_pass 指定上游server的地址
mirror配置
internal 指定此location只能被“内部的”请求调用,外部的调用请求会返回”Not found” (404) proxy_pass 指定上游server的地址 proxy_set_header 设置镜像流量的头部
不允许复制post请求
默认是支持post复制的,需要通过配置来禁止
server {
listen 80;
server_name web1.www.com;
# 源站配置
location / {
access_log /data/nginx/1.14.1/logs/web1/access.log accesslog;
mirror /mirror;
mirror_request_body off;# Indicates whether the client request body is mirrored. default value is on.
proxy_pass http://web1.upstream.name;
}
# 镜像站点配置
location /mirror {
# 判断请求方法,不是GET返回403
if ($request_method != GET) {
return 403;
}
internal; # 内部配置
proxy_pass http://mirror.web1.upstream.name$request_uri;
proxy_pass_request_body off; # Indicates whether the original request body is passed to the proxied server. default value is on
proxy_set_header Content-Length ""; # mirror_request_body/proxy_pass_request_body都设置为off,则Conten-length需要设置为"",否则有坑
proxy_set_header X-Original-URI $request_uri; # 使用真实的url重置url
}
}
流量放大配置方法
配置多分mirror
server {
listen 80;
server_name web1.www.com;
# 源站配置
location / {
access_log logs/access.log accesslog;
mirror /mirror;
# 多加一份mirror,流量放大一倍
mirror /mirror;
mirror_request_body on;# Indicates whether the client request body is mirrored. default value is on.
proxy_pass http://web1.upstream.name;
}
# 镜像站点配置
location /mirror {
internal; # 内部配置
proxy_pass http://mirror.web1.upstream.name$request_uri;
proxy_pass_request_body on; # Indicates whether the original request body is passed to the proxied server. default value is on
proxy_set_header X-Original-URI $request_uri; # reset uri
}
}
配置两组后台服务器,http://backend指向生产服务器, http://test_backend指向测试服务器。
用户访问生产服务器的同时,请求会被nginx复制发送给测试服务器,需要注意的一点是mirror不会输出http返回内容。