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

Nginx 禁止特定目錄執行 PHP 腳本配置指南

編輯:關於伺服器

核心配置

利用 location 正則匹配攔截特定目錄下的 PHP 檔案請求,直接回傳 403。

基本範例:單一/多個目錄

# 禁止 attachments、images 目錄執行 PHP
location ~* ^/(attachments|images)/.*\.(php|php5|PHP|PHP5)$ {
    deny all;
}

進階範例:子目錄/多專案環境

# 針對 /discuz/、/bbs/ 專案下的上傳目錄
location ~* ^(/discuz/|/bbs/)/(attachments|images)/.*\.(php|php5|PHP|PHP5)$ {
    deny all;
}

關鍵點解析

  • ~*:不區分大小寫匹配(涵蓋 .php、.PHP、.Php 等)
  • ^/(...)/:錨定路徑開頭,避免誤匹配同名子目錄
  • (attachments|images):群組匹配多個敏感目錄名
  • .*\.(php|php5|PHP|PHP5)$:匹配任意 PHP 副檔名結尾
  • deny all;:直接拒絕,回傳 403 Forbidden

部署位置建議

  1. server 區塊內:針對單一虛擬主機生效(推薦)
  2. http 區塊內:全域生效,需謹慎評估影響範圍
  3. 配置完成後:nginx -t && nginx -s reload

擴充應用

# 禁止上傳目錄執行任何腳本類副檔名
location ~* ^/uploads/.*\.(php|php5|phtml|phar|jsp|asp|aspx|py|pl|cgi)$ {
    deny all;
    access_log off;  # 可選:不記錄存取日誌
}

# 僅允許特定 IP 存取管理後台
location ^~ /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.5;
    deny all;
    # PHP 處理規則...
}

對比 Apache

Apache 需在 .htaccess 或 <Directory> 使用 RemoveHandler / php_flag engine off,語法較繁瑣且易被覆寫。Nginx 以單一 location 規則即可集中管理,維護性極佳。

Copyright © Windows教程網 All Rights Reserved