温馨提示×

centos怎样禁止apache目录浏览

小樊
41
2026-10-11 20:06:08
栏目: 智能运维

在 CentOS 上禁止 Apache 的目录浏览(即禁止访问未设置默认首页的目录时列出文件列表),核心就是关闭 Indexes 选项。下面按常见场景说明。


一、临时/快速禁止(推荐)

1. 修改 Apache 主配置或虚拟主机配置

编辑配置文件(根据系统实际情况选择):

# CentOS 6/7 常见路径
vi /etc/httpd/conf/httpd.conf

# 或虚拟主机
vi /etc/httpd/conf.d/xxx.conf

找到类似内容:

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

将 Indexes 删除或改为 -Indexes:

Options -Indexes FollowSymLinks

✅ 含义:

  • Indexes:开启目录浏览
  • -Indexes:禁止目录浏览

二、使用 .htaccess 禁止(适合不能改主配置)

1. 确保 AllowOverride 已开启

<Directory "/var/www/html">
    AllowOverride All
</Directory>

2. 在网站根目录创建/修改 .htaccess

vi /var/www/html/.htaccess

添加:

Options -Indexes

三、针对某个目录单独禁止

例如禁止 /var/www/html/upload 目录浏览:

<Directory "/var/www/html/upload">
    Options -Indexes
</Directory>

四、重启 Apache 生效

# CentOS 6
service httpd restart

# CentOS 7/8
systemctl restart httpd

五、验证是否成功

访问一个没有默认首页的目录,例如:

http://服务器IP/images/

✅ 成功效果:

403 Forbidden

❌ 失败效果:

文件列表被列出

六、补充建议(安全)

  • 同时建议关闭:Options -Indexes -Includes
  • 可配合:
    DirectoryIndex index.php index.html
    
  • 生产环境避免 AllowOverride All

如果你用的是 CentOS + SELinux 或 Apache + PHP-FPM,我也可以给你更针对性的配置。

0 踩