Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Nginx 訪問控制:允許/拒絕指定 IP 的配置規則與匹配順序詳解

編輯:Linux 教學

使用 ngx_http_access_module 實現 IP 訪問控制。規則按聲明順序匹配,首條匹配生效。

基本語法

allow  IP|CIDR|all;
deny   IP|CIDR|all;

示例:僅允許特定網段,排除單個 IP

location / {
    deny 192.168.1.1;          # 拒絕單個 IP
    allow 192.168.1.0/24;      # 允許該網段
    allow 10.1.1.0/16;         # 允許另一網段
    deny all;                  # 拒絕其他所有
}

效果:192.168.1.1 被拒絕;192.168.1.2-254 和 10.1.1.0/16 允許;其餘拒絕。

常見錯誤:順序顛倒導致規則失效

location / {
    deny all;                  # 第一條就拒絕所有
    allow 192.168.1.0/24;      # 永遠不會生效
}

與 Apache Order Allow,Deny 不同,Nginx 無全局排序概念,嚴格按配置文件順序自上而下匹配。

進階:結合 Geo 模塊實現複雜邏輯

geo $block_ip {
    default 0;
    192.168.1.1 1;
    10.0.0.0/8 1;
}
server {
    if ($block_ip) { return 403; }
}

適合大量 IP 名單維護,配置更清晰。

Copyright © Windows教程網 All Rights Reserved