V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
SoulFlame
V2EX  ›  问与答

请教如何方便有效的封禁国外 IP

  •  
  •   SoulFlame · 18 天前 · 1158 次点击
    我的 API 只服务于国内,时不时有国外 IP 捣乱,请问怎么封国外的 IP 啊?
    10 条回复    2025-07-18 16:31:32 +08:00
    HUZHUANGZHUANG
        1
    HUZHUANGZHUANG  
       18 天前
    api 应该是通过域名来访问的吧?把域名托管到 CF,在安全工具那里可以通过区域来禁止访问的。你试试这样有没有效果。
    happyxhw101
        2
    happyxhw101  
       18 天前
    如果用的是 nginx 代理,可以这么干

    1. nginx 配置 geo-ip
    ```
    load_module "modules/ngx_http_geoip_module.so";
    load_module "modules/ngx_stream_geoip_module.so";
    ```

    2. 映射国家 code
    ```
    map $geoip_country_code $allowed_country {
    default yes;
    CN yes;
    }

    map $remote_addr $allowed {
    default $allowed_country;
    127.0.0.1 yes;
    ~^192\.168\.\\d+\.\\d+$ yes;
    ~^192\.167\.0\.\\d+$ yes;
    ~^192\.166\.1\.\\d+$ yes;
    }
    ```

    3. 判断 allowed
    ```
    server {
    listen 443 ssl;
    if ($allowed != yes) {
    return 404;
    }
    }
    ```
    happyxhw101
        3
    happyxhw101  
       18 天前
    @happyxhw101 写错了
    map $geoip_country_code $allowed_country {
    default no;
    CN yes;
    }
    happyxhw101
        4
    happyxhw101  
       18 天前
    tcp 也是可以的,用 nginx 的 stream, 比如代理 ssh
    ```
    map $allowed $ssh_server {
    yes ssh;
    }

    upstream ssh {
    server 192.168.5.1:12345;
    }

    server {
    listen 2345;
    listen [::]:2345;
    proxy_pass $ssh_server;
    proxy_connect_timeout 30s;
    proxy_timeout 60s;

    ssl_preread on;
    }
    ```
    BeforeTooLate
        5
    BeforeTooLate  
       18 天前
    dns 解析的时候,直接把境外地址 CNAME 到 google.com
    SoulFlame
        6
    SoulFlame  
    OP
       18 天前
    @HUZHUANGZHUANG #1 域名在阿里管理,不方便托管到 CF
    SoulFlame
        7
    SoulFlame  
    OP
       18 天前
    @BeforeTooLate #5 请问在哪里设置,我域名在阿里
    SoulFlame
        8
    SoulFlame  
    OP
       18 天前
    @happyxhw101 #2 请问这个原理是不是通过别人维护的 ip 名单实现的啊?
    BeforeTooLate
        9
    BeforeTooLate  
       18 天前   ❤️ 1
    @SoulFlame 阿里云解析请求来源这个部分可以选择境外这个选项吧,具体我不太清楚这样是否有用
    SoulFlame
        10
    SoulFlame  
    OP
       18 天前
    @BeforeTooLate #9 非常感谢,我上去看了,阿里 DNS 解析 请求来源是有地域设置,可以选中国
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3400 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 04:54 · PVG 12:54 · LAX 21:54 · JFK 00:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.