织梦nginx禁止访问目录列表
问题背景
nginx 在没有 index 指定的目录被访问时,如果开启了 autoindex on;,会列出该目录下所有文件。织梦 DedeCMS 站点的 /data/、/uploads/allimg/、/templets/ 等目录如果没有禁止列表,访问者可以直接浏览文件结构,泄露模板文件、备份文件、上传内容清单,是典型的安全风险。
原因分析
autoindex 默认行为
nginx 默认 autoindex off,但如果某个 server 或 location 块中显式开启了 on,且该目录没有 index 文件,就会列出目录内容。
index 指令缺失
nginx 默认 index index.html index.htm,若目录中无 index 文件且 autoindex off,会返回 403。这是相对安全的默认状态,但部分管理员为了调试方便临时开启 autoindex 后忘记关闭。
解决步骤
一、全局关闭 autoindex
在 nginx.conf 的 http 块中确认:
http {
autoindex off;
# ...
}
这样所有 server/location 默认不允许目录列表。
二、敏感目录单独 deny
织梦敏感目录直接禁止外部访问:
# 禁止访问 data 目录(含数据库配置、缓存、上传配置)
location ~* ^/(data|include|dede|member|plus|special|templets)/ {
deny all;
# 但允许 PHP 内部 include,外部直接访问全部 403
}
# uploads 目录允许访问图片,但禁止 PHP 执行
location ~* ^/uploads/.*\.(php|php3|php5|phtml)$ {
deny all;
}
location ~* ^/uploads/ {
# 静态文件正常访问
}
三、目录无 index 文件返回 403
如果目录下确实没有 index 文件,又不希望列出:
location /some-dir/ {
autoindex off;
# 没有 index 时返回 403
}
四、使用 try_files 控制默认页
location / {
try_files $uri $uri/ /index.php?$query_string;
}
这样目录请求会被 try_files 转发到 index.php,不会列出文件。
五、完整织梦 nginx 安全配置示例
server {
listen 80;
server_name www.example.com;
root /var/www/dedecms;
# 全站关闭目录列表
autoindex off;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 敏感目录全部 403
location ~* ^/(data|include|templets|dede|member)/ {
deny all;
}
# uploads 仅允许静态文件
location ~* ^/uploads/.*\.(php|phtml|pl|py|sh)$ {
deny all;
}
# PHP 处理
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
配置示例汇总
核心三步:全局 autoindex off → 敏感目录 deny all → uploads 禁止 PHP 执行。配置后用 curl 验证
https://www.example.com/data/ 返回 403。注意事项
location ~是正则匹配,^/(data|include)/不要漏写^,否则会误匹配/news/data/等正常路径。- nginx 配置修改后必须
nginx -t验证语法,再nginx -s reload。 - uploads 目录禁止 PHP 执行是防止 webshell 的关键,必须严格执行。
- CDN 与 WAF 可能在 nginx 前面拦截,需同时检查 CDN 的目录列表配置。
- 开启 HTTP/2 时,目录 deny 返回的 403 仍会暴露 server 信息,建议同时关闭 server_tokens。
实施建议
建议把织梦 nginx 安全配置做成一份独立 include 文件 dedecms_security.conf,所有织梦站点统一 include,避免每个站点重复维护。每月用 nmap 或在线扫描工具对站点做一次目录扫描,确认敏感目录均返回 403/404 而非 200。同时把 data、dede 等关键目录改名后同步更新 nginx 规则,配合目录改名策略,让站点安全基线持续提升。