Home > other >  Use conditional mirror in Nginx
Use conditional mirror in Nginx

Time:12-05

Here is my Nginx configuration:

upstream backend {
    server backend.local:10000;
}

upstream test_backend {
    server test.local:20000;
}

server {
    server_name proxy.local;
    listen 8000;

    location / {
        if ($http_authorization != "") {
            mirror /mirror;
        }
        proxy_pass http://backend;
    }

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

As you can see, I tried to wrap the mirror block with a condition. Basically I need to mirror the request whenever the Authorization header is set. Nginx shows and error when I try to use this config which tells me that I can't use mirror inside an if statement. How can I mirror the request conditionally?

CodePudding user response:

You could create synthetic ^/http_auth location and rewrite the requests with http authorization to those location. For example:

...
    if ($http_authorization) {
        rewrite ^/(.*)$ /http_auth/$1 last;
    }

    location ~ ^/http_auth/(.*)$ {
        proxy_pass http://backend;
    }

    location / {
        mirror /mirror;
        proxy_pass http://backend;
    }
...
  • Related