萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx 針對特定目錄實施 IP 存取控制(允許內網、拒絕外網)

場景

保護 phpmyadmin、download 等敏感目錄,僅允許內網 IP(如 192.168.1.0/24)存取,外網 IP 直接拒絕。

關鍵原理:location 優先權

Nginx location 匹配優先順序:

  1. = 精確匹配
  2. ^~ 前綴匹配(不再嘗試正則)
  3. ~/~* 正則匹配
  4. / 通用匹配

使用 ^~ /phpmyadmin/ 確保優先於通用 location / 與 PHP 正則 location 生效,避免被後者攔截導致 404/500。

完整設定範例 1:巢狀 location(推薦)

server {
    listen 80;
    server_name example.com;
    access_log logs/access.log main;

    # 通用站點根目錄
    location / {
        root html;
        index index.php index.html index.htm;
    }

    # 受保護目錄:phpmyadmin
    location ^~ /phpmyadmin/ {
        allow 192.168.1.0/24;  # 允許內網
        deny all;              # 拒絕其餘

        # 內層處理 PHP
        location ~ \.php$ {
            root /var/mailapp/nginx/html;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi_params;
        }
    }

    # 通用 PHP 處理
    location ~ \.php$ {
        root /opt/nginx/html;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

完整設定範例 2:獨立 location + 內層 PHP

server {
    listen 80;
    server_name example.com;
    access_log logs/access.log main;

    location / {
        root html;
        index index.php index.html index.htm;
    }

    location ^~ /download/ {
        allow 192.168.1.0/24;
        deny all;
        index index.php index.html index.htm;

        location ~ \.php$ {
            root /var/mailapp/nginx/html;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi_params;
        }
    }

    location ~ \.php$ {
        root /opt/nginx/html;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

常見陷阱與解法

問題原因解法
受保護目錄下 PHP 回傳 404外層 location ~ \.php$ 搶先匹配,root 指向錯誤路徑在受保護目錄 location 內再定義一層 location ~ \.php$
允許 IP 仍被拒絕IP 格式錯誤或 CIDR 寫法不支援確認用 192.168.1.0/24 格式,或單一 IP 192.168.1.100
修改後不生效未重新載入 Nginxnginx -t && nginx -s reload

驗證指令

# 測試內網 IP(應回傳 200/403 視目錄權限)
curl -I https://example.com/phpmyadmin/

# 測試外網 IP(應回傳 403)
curl -I --interface eth0 https://example.com/phpmyadmin/
copyright © 萬盛學電腦網 all rights reserved