如何将允许/拒绝与 set_real_ip_from 结合使用?

Jay*_*Jay 5 ip nginx reverse-proxy

我的 nginx 后端服务器应该只接受来自我的前端 1.2.3.4 的请求。但是,我也希望 nginx 记录正确的 IP 地址,所以我使用set_real_ip_from. 但是这样做,allow配置中的规则不匹配,nginx 将始终返回 403。这是相关的配置:

allow  1.2.3.4;
deny  all;

set_real_ip_from  1.2.3.4;
real_ip_heaader  X-Real-IP;
Run Code Online (Sandbox Code Playgroud)

我怎样才能克服这个问题?

小智 4

我自己一直在寻找这个问题,因为我花了“一段时间”才找到解决方案,所以我将其放在这里以方便其他人。

允许/拒绝结构在这种情况下不起作用,因为它们不适用于真实的 ip 变量。

相反,您可以使用$http_x_forwarded_for变量:

## this goes before server section
## it allows us to check if forwarded ip is allowed to make request or not
map $http_x_real_ip $allowed {
    default false;

    ## your ip goes here
    ~\s111.111.111.111 true;
    ## other ips you want to allow
}

server {
    ## ... other instructions...

    set_real_ip_from  1.2.3.4;
    real_ip_header  X-Forwarded-For;

    ## you may want to add this to get "truly" real ip
    real_ip_recursive  on;

    ## ... other instructions...

    ## or any other location you need
    location / {
        if ($allowed = false) {
            return 403;
        }
        ## ... other instructions...
    }
}
Run Code Online (Sandbox Code Playgroud)