在 Ubuntu 的 Apache2 中,禁止目录浏览(目录列表)通常有以下几种方式,最常用的是 关闭 Indexes 选项。
编辑你的站点配置,例如:
sudo nano /etc/apache2/sites-available/000-default.conf
或你的自定义配置文件。
在 <Directory> 段中,确保 没有 Indexes,或显式关闭它:
<Directory /var/www/html>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
✅ 关键点是:
Options -Indexes
-Indexes:禁止目录浏览+FollowSymLinks:允许符号链接(可选)保存后重启 Apache:
sudo systemctl restart apache2
编辑主配置:
sudo nano /etc/apache2/apache2.conf
找到类似:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
改为:
<Directory /var/www/>
Options -Indexes +FollowSymLinks
AllowOverride None
Require all granted
</Directory>
然后重启 Apache。
.htaccess 文件(适合无法修改主配置的情况)确保 Apache 允许 .htaccess 覆盖:
AllowOverride All
然后在网站根目录创建或编辑 .htaccess:
nano /var/www/html/.htaccess
添加:
Options -Indexes
✅ 无需重启 Apache,立即生效。
访问一个 没有 index 文件(如 index.html / index.php)的目录:
http://your-server-ip/testdir/
❌ 只想删除 index.html 却看到目录列表
✅ 必须显式禁用 Indexes
❌ 修改配置后没重启 Apache
✅ 一定要执行:
sudo systemctl restart apache2
✅ 最佳实践:
Options -Indexes
放在:
.htaccess(灵活但略慢)如果你愿意,我可以帮你检查 具体配置文件内容,直接告诉你该怎么改。