首页 > 解决方案 > NGINX 根据 $arg 限制 IP 地址

问题描述

使用 nginx,我如何根据 $args 的正则表达式限制某些 IP 地址

例如

对于https://somewhere.invalid/login URI 位置

location /login {
    allow 1.2.3.4;
    deny all;
}

说得通

但是我如何允许 /login 只受 IP 限制,其中 $args = "person=super"

eq https://somewhere.invalid/login?person=super

nginx 不允许在“if”块中使用“allow”语句。

location /login {
    allow all;
    if ( $args ~ /person=super/ ) {
        allow 1.2.3.4;
        deny all;
    }
}

如果位置块 / 是 proxy_pass 有什么区别吗?

标签: nginx

解决方案


正如文档所说 allowdeny指令不能在if上下文中使用。允许的上下文是httpserverlocationlimit_except。但是,您可以通过两个map块检查$arg_person$remote_addr变量值来实现相同的行为:

map $arg_person $deny {
    super    $checkip;
    # default value will be an empty string
}
map $remote_addr $checkip {
    1.2.3.4  '';
    # you can add other allowed IPs here
    default  1;
}

server {
    ...
    location /login {
        if ($deny) { return 403; }
        ...
    }
}

推荐阅读