温馨提示×

ubuntu apache如何禁止目录浏览

小樊
45
2026-09-17 09:22:41
栏目: 智能运维

在 Ubuntu 上使用 Apache 时,**禁止目录浏览(目录列表)**通常是通过关闭 Indexes 选项来实现的。以下是常见做法:


方法一:修改 Apache 全局配置(推荐)

  1. 编辑 Apache 主配置或虚拟主机配置
sudo nano /etc/apache2/apache2.conf

或(更常见)

sudo nano /etc/apache2/sites-available/000-default.conf
  1. 确保 Directory 配置中包含:
<Directory /var/www/html>
    Options -Indexes +FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

关键是:

  • -Indexes:禁止目录浏览
  • +Indexes:开启目录浏览(不要这样写)
  1. 保存后重启 Apache:
sudo systemctl restart apache2

方法二:使用 .htaccess(适合不能改主配置)

  1. 确认 Apache 允许 .htaccess 覆盖
    apache2.conf 中:
<Directory /var/www/html>
    AllowOverride All
</Directory>
  1. 在网站根目录创建/编辑 .htaccess
nano /var/www/html/.htaccess

添加:

Options -Indexes
  1. 重启 Apache(如有必要):
sudo systemctl restart apache2

验证是否生效

访问一个没有 index 文件的目录,例如:

http://your-server-ip/test/
  • 若看到 403 Forbidden ✅ 成功
  • 若看到文件列表 ❌ 未生效

补充:只禁止某个目录

<Directory /var/www/html/uploads>
    Options -Indexes
</Directory>

如果你愿意,可以贴出你的 Apache 配置或虚拟主机文件,我可以帮你精确修改。

0