Skip to content

Mirroring requests to another server with Nginx

If you want to duplicate your traffic on your Nginx server to another server you will need to create mirror location. This is very useful if you want to debug all your requests.

Creating a Mirror

Create a group of backend servers we’ll mirror all requests to.

upstream backend_mirrors {
     server host1.example.com
}

Modify the location you want to mirror all requests. Add the new mirror directive. If you would like to mirror the entire request body, add the new mirror_request_body directive, too.

location / {
     mirror /mirror;
     mirror_request_body on;
     root /usr/share/nginx/html;
     index index.html index.html
}

Set up a mirror that accepts internal access only. This prevents others from
being able to access /mirror directly from the Internet. The requested URI will be sent to the mirror.

location /mirror {
     internal;
     proxy_pass https://backend_mirrors;
     proxy_set_header X-SERVER-PORT $server_port;
     proxy_set_header X-SERVER-ADDR $server_addr;
     proxy_set_header HOST $http_host;
     proxy_set_header X-REAL-IP $remote_addr;
}

After you finished, type nginx -t to verify your nginx config syntax. If everything is ok, you will get this message:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restart Nginx to apply your changes.

Published inLinuxNginx