在 Nginx 中使用条件镜像

Use conditional mirror in Nginx

这是我的 Nginx 配置:

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;
    }
}

如您所见,我尝试用条件包裹 mirror 块。基本上,每当设置 Authorization header 时,我都需要镜像请求。当我尝试使用此配置时,Nginx 显示错误,告诉我不能在 if 语句中使用 mirror。如何有条件地镜像请求?

您可以创建合成 ^/http_auth 位置,并使用对该位置的 http 授权重写请求。 例如:

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

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

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