拦截所有Nginx位置以进行身份​​验证

时间:2020-10-14 15:33:20

标签: nginx

我想知道如何在一个位置为每个位置显式设置身份验证检查。像下面这样做似乎容易出错(缺少输入项,错别字,不必要的重复等)

nginx.conf

location / {
 auth_request /someAuth;
 auth_request_set $someVar $someOtherVar;
 proxy_pass https://somewhere.com:1234;
 proxy_set_header X-Forwarded-For $remote_addr;
}

location /foo {
 auth_request /someAuth;
 auth_request_set $someVar $someOtherVar;
 proxy_pass https://somewhereElse.com:6578;
 proxy_set_header X-Forwarded-For $remote_addr;
}

location /bar {
 auth_request /someAuth;
 auth_request_set $someVar $someOtherVar;
 proxy_pass https://somewhereOther.com:9876;
 proxy_set_header X-Forwarded-For $remote_addr;
}

1 个答案:

答案 0 :(得分:2)

也许以类似的方式使用map指令

map $uri $proxy {
    ~^/foo    https://somewhereElse.com:6578;
    ~^/bar    https://somewhereOther.com:9876;
    default   https://somewhere.com:1234;
}
server {
    ...
    location / {
        auth_request /someAuth;
        auth_request_set $someVar $someOtherVar;
        proxy_pass $proxy;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

请注意,这种配置需要使用resolver指令。