如果还需要同时覆盖 uploads 和 static 目录,有两种写法,任选其一。
将以下规则放入对应站点的 server { } 块中:
# 禁止 upload 及子目录下的 PHP 文件被访问/执行
location ~* ^/upload/.*\.php$ {
deny all;
access_log off;
log_not_found off;
}
# 禁止 upload / uploads / static 及子目录下的 PHP 文件被访问/执行
location ~* ^/(?:upload|uploads|static)/.*.php$ {
deny all;
access_log off;
log_not_found off;
}(?:...) 是非捕获分组,只做逻辑分组、不额外产生捕获,匹配效率略好。
^/(?:upload|uploads|static)/ 要求目录名完整匹配:/upload/、/uploads/、/static/ 都能命中,但 /upload123/ 这种不会被误伤。
同样只拦截 .php 结尾的请求,三个目录下的图片、css、js 等静态资源不受影响。
location ~* ^/upload/.*.php$ {
deny all;
access_log off;
log_not_found off;
}
location ~* ^/uploads/.*.php$ {
deny all;
access_log off;
log_not_found off;
}
location ~* ^/static/.*.php$ {
deny all;
access_log off;
log_not_found off;
}顺序:以上规则必须放在 location ~ .php$ { fastcgi_pass ... } 之前。Nginx 正则 location 按出现顺序匹配,先命中先生效。
验证:改完先 nginx -t && nginx -s reload,然后分别访问 /upload/x.php、/uploads/2026/a.php、/static/img/b.php,都应返回 403;同时访问同目录下的图片应正常。
如果你的目录可能出现在多级路径中(比如 /data/upload/... 这种),把正则开头的 ^/ 改成 ^/.*?/(?:upload|uploads|static)/ 即可,但要注意别误伤其它路径。