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

Nginx 目錄級 IP 存取控制:phpMyAdmin 內網限制實戰

編輯:關於伺服器

核心需求

phpMyAdmin 等敏感管理介面僅允許內網 IP 存取,拒絕公網存取,同時保持主站正常對外服務。

關鍵技術點:Location 優先級

  • location ~ ^/phpmyadmin/ (正則) 優先級 高於 location / (前綴)
  • 巢狀 location 繼承父層處理邏輯,需在子區塊重新定義 fastcgi

完整配置範例

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 處理 (必須重新定義,否則繼承外層導致 404)
        location ~ \.php$ {
            root /var/www/html;  # phpMyAdmin 實際路徑
            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;
    }
}

替代寫法:下載目錄限制

location ~ ^/download/ {
    allow 192.168.1.0/24;
    deny all;
    index index.php index.html;
    
    location ~ \.php$ {
        root /var/www/html;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

IP 匹配語法速查

語法範例說明
單一 IPallow 192.168.1.100;精確匹配
CIDR 網段allow 192.168.1.0/24;256 個 IP
子網路遮罩 (舊)allow 192.168.1.0/255.255.255.0;等同 /24
多條規則allow 10.0.0.0/8; allow 192.168.0.0/16;順序執行,匹配即停止
預設拒絕deny all;必須放在 allow 之後

進階:地理位置模組 (ngx_http_geoip_module)

# http 區塊
geoip_country /usr/share/GeoIP/GeoIP.dat;

# server 區塊
location ~ ^/admin/ {
    # 僅允許台灣 IP
    if ($geoip_country_code != "TW") {
        return 403;
    }
    # ...
}

驗證與除錯

# 測試配置語法
nginx -t

# 模擬不同 IP 存取 (需安裝 ngx_http_realip_module 並設定 real_ip_header)
curl -H "X-Forwarded-For: 192.168.1.50" https://example.com/phpmyadmin/
curl -H "X-Forwarded-For: 203.0.113.10" https://example.com/phpmyadmin/

# 查看錯誤日誌
tail -f /var/log/nginx/error.log

常見錯誤

  • 忘記在限制區塊內重新定義 location ~ \.php$ → PHP 檔案直接下載或 404
  • allow/deny 順序錯誤 → 全部被允許或全部被拒絕
  • 使用 location /phpmyadmin/ (前綴) 而非正則 → 無法正確攔截子路徑
Copyright © Windows教程網 All Rights Reserved