You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nginx环境下禁用目录中的PHP执行权限?

Nginx 替代 Apache .htaccess 阻止可执行文件的方案

你之前在 Apache 中通过目录下的 .htaccess 文件阻止指定后缀的可执行文件,对应的配置代码如下:

# Block executables
<FilesMatch "\.(php|phtml|php3|php4|php5|pl|py|jsp|asp|html|htm|shtml|sh|cgi|suspected)$">
    deny from all
</FilesMatch>

切换到 Nginx 后,可通过以下两种方式实现相同效果:

1. 全局站点生效

在 Nginx 的 server 配置块中添加规则,对整个站点内的指定后缀文件进行拦截:

# 拦截指定后缀的可执行文件访问
location ~* \.(php|phtml|php3|php4|php5|pl|py|jsp|asp|html|htm|shtml|sh|cgi|suspected)$ {
    deny all;
    return 403;
}

2. 针对特定目录生效

如果仅需对某个目录(比如上传目录 /uploads/)生效,可嵌套对应的 location 块:

location /uploads/ {
    # 此处可添加该目录的其他配置(如静态文件缓存规则等)
    
    # 拦截目录内的指定后缀文件
    location ~* \.(php|phtml|php3|php4|php5|pl|py|jsp|asp|html|htm|shtml|sh|cgi|suspected)$ {
        deny all;
        return 403;
    }
}

操作注意

  • 修改配置后,先执行 sudo nginx -t 验证语法是否正确
  • 验证通过后,执行 sudo nginx -s reload 重载 Nginx 使配置生效

内容的提问来源于stack exchange,提问作者Mk1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 05:24:55