防止攻擊者上傳惡意腳本偽裝成圖片/文檔,或直接下載 .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;
}
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/單一入口應用**。# 全站靜態資源正常
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;
}
include security.conf;。security.limit_extensions = .php(預設值),禁止解析 .php5 等變體。noexec,nodev,nosuid。