且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不使用if的情况下阻止某些国家(geoip2)的页面?

更新时间:2023-09-16 15:12:34

NGINX官方文章

An official NGINX article says:


在位置上下文中,可能在内部完成的唯一100%安全的事情是:

The only 100% safe things which may be done inside if in a location context are:

return ...;
rewrite ... last;


所以您的 if(...){返回503 ; } 块是完全安全的。要排除第一个 if 块,请使用

So your if (...) { return 503; } block is completely safe. To exclude first one if block, use

geo $lan {
    default no;
    123.224.55.2 yes;
}
map $geoip2_data_country_code $allowed_country {
    default no;
    UA yes;
    BG yes;
    RO yes;
}
map $lan$allowed_country $deny {
    ~yes "";
    default 1;
}
...
server {
    ...
    if ($deny) {
        return 503;
    }
    ...
}

更新

此版本具有相同的功能,并且由于未使用正则表达式匹配,因此应稍快一些:

This version have the same functionality and should be slightly faster since it doesn't use a regex matching:

geo $lan {
    default  0;
    123.224.55.2  1;
    ...
}
map $geoip2_data_country_code $allowed_country {
    default  0;
    UA  1;
    BG  1;
    RO  1;
}
map $lan$allowed_country $deny {
    default  0;
    00  1;
}
...
server {
    ...
    if ($deny) {
        return 503;
    }
    ...
}