How to implement partial mirroring in nginx?

Solution 1:

If you have two web servers and you want to send 30% of the requests to server A and 70% of the requests to server B you can put a load balancer in front of the two web server. You have to put a load balancer in front of the two web servers anyway otherwise all traffic will only go to one server or the other.

Using weights you can specify how much traffic should go to the first or the second server. A simple example is given below:

http {
  upstream myapp1 {
    server srv1.example.com weight=3;
    server srv2.example.com weight=7;
  }
  server {
    listen 80;
    location / {
      proxy_pass http://myapp1;
    }
  }
}

EDIT: With both servers being the production server you can use the mirror module on srv1.example.com to send 30% of the traffic to your test server. Agreed, this is a bit of a dirty hack so feel free to down-vote when better solutions are given.

EDIT 2: assign the samen IP address to both DNS A records if you only have one server.

Solution 2:

http {
  ...
  split_clients "${remote_addr}AAA" $mirror_allowed {
    30% 1;
    * "";
  }
}

server {
  ...
  location / {
    ...
    mirror /mirror;
  }

  location /mirror {
    internal;
    if ($mirror_allowed = "") { 
      return 200; 
    }
    proxy_pass https://some.mirror.endpoint$request_uri;
  }
}