萬盛學電腦網

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

Nginx 限制僅允許執行 PHP 腳本,禁止直接訪問靜態敏感檔案配置方案

場景

防止攻擊者上傳惡意腳本偽裝成圖片/文檔,或直接下載 .sql、.bak、.conf 等敏感檔案。

方案一:黑名單封鎖特定副檔名

location ~* \.(txt|doc|sql|gz|bak|conf|inc)$ {
    if (-f $request_filename) {
        break;   # 交給下一條 location 處理(通常返回 404)
    }
    return 404;
}

# 或更徹底直接拒絕
location ~* \.(txt|doc|sql|gz|bak|conf|inc)$ {
    deny all;
}

方案二:白名單僅允許 PHP 入口(推薦)

server {
    listen 80;
    server_name www.example.com;
    root /var/www/vhosts/www.example.com;

    location / {
        index index.php;

        # 預設標記為非 PHP
        set $is_php 'no';

        # 檔案不存在 → 交給 PHP (前端控制器模式)
        if (!-f $request_filename) {
            set $is_php 'yes';
        }

        # 副檔名為 .php 及其變體
        if ($request_filename ~ \.php($|/)) {
            set $is_php 'yes';
        }

        # 非 PHP 請求直接 404
        if ($is_php = 'no') {
            return 404;
        }

        # 其餘交給 FastCGI
        fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    access_log /var/log/nginx/www.example.com.access.log;
}

原理解析

  • set $is_php 變數預設 no。
  • 請求檔案不存在(如框架路由)或副檔名為 .php → 標記 yes。
  • 最終 if ($is_php = 'no') 直接返回 404,繞過 FastCGI,靜態檔案(js/css/jpg)也被擋住。**注意**:此方案會導致所有靜態資源 404,**僅適合純 API/單一入口應用**。

方案三:靜態資源正常服務,僅限制上傳目錄執行 PHP(最通用)

# 全站靜態資源正常
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

# 上傳/用戶目錄:禁止執行 PHP、腳本
location ~* /(uploads|data|attachment)/.*\.(php|php5|phtml|phar)$ {
    deny all;
    return 403;
}

# 敏感檔案直接 404
location ~* /\.(git|svn|env|htaccess|htpasswd) {
    deny all;
}
location ~* \.(sql|bak|conf|ini|log)$ {
    deny all;
}

最佳實踐建議

  1. **應用層面**:上傳檔案重命名、存放非 Web 目錄、驗證 MIME/副檔名/魔數。
  2. **Nginx 層面**:方案三部署於所有站點通用配置片段 include security.conf;。
  3. **PHP-FPM 層面**:security.limit_extensions = .php(預設值),禁止解析 .php5 等變體。
  4. **檔案系統層面**:上傳目錄掛載 noexec,nodev,nosuid。
copyright © 萬盛學電腦網 all rights reserved