How to Mirror Traffic in NGINX

mirror traffic in nginx

Sometimes, you might want to redirect incoming traffic to not one, but two or more, web servers. This can be really tedious to setup from scratch. Luckily NGINX provides an http_mirror_module to mirror your traffic which you can send to multiple pages. Let us take a look at how to mirror traffic in NGINX.


How to Mirror Traffic in NGINX

Here are the steps to mirror traffic in NGINX.


1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation



$ sudo vim /etc/nginx/nginx.conf


2. Mirror Traffic

Let’s say you have incoming traffic that you want to mirror to servers A and B. In that case, just add the following lines to your NGINX config file

location / {
  mirror /mirror;
  proxy_pass http://backend;

location = /mirror {
  proxy_pass http://test_backend$request_uri;

In the above code, NGINX will send incoming traffic to /mirror as well as proxy it to backend servers, thereby mirroring your traffic.

In /mirror location, it has another proxy_pass directive to handle the mirrored traffic.

So you will need to setup 2 proxy_pass backend servers to handle original and mirrored traffic.



3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t


If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload


That’s it! Now NGINX will easily mirror your incoming traffic to multiple back-end servers.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!