温馨提示×

ubuntu apache2如何禁止目录

小樊
44
2026-09-11 03:06:37
栏目: 智能运维

在 Ubuntu 的 Apache2 中,“禁止目录”通常有以下几种常见需求,你可以根据具体情况选择:


一、禁止目录列表(防止浏览器看到目录文件列表)

默认情况下,如果目录下没有 index.html 等文件,Apache 可能会列出文件。

方法 1:修改 Apache 配置(推荐)

编辑站点配置,例如:

sudo nano /etc/apache2/sites-available/000-default.conf

<VirtualHost><Directory> 中加入:

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

保存后重启 Apache:

sudo systemctl restart apache2

方法 2:使用 .htaccess

在目标目录下创建 .htaccess 文件:

nano /var/www/html/.htaccess

写入:

Options -Indexes

确保 Apache 允许 .htaccess

AllowOverride All

二、完全禁止访问某个目录(返回 403)

方法:使用 <Directory>.htaccess

配置文件方式

<Directory /var/www/html/private>
    Require all denied
</Directory>

.htaccess 方式

/var/www/html/private/.htaccess 中写:

Require all denied

三、禁止访问特定目录下的某种文件

例如禁止访问 .inc 文件:

<Files ~ "\.inc$">
    Require all denied
</Files>

四、禁止某个 URL 路径(如 /admin)

<Location /admin>
    Require all denied
</Location>

五、验证配置是否正确

sudo apache2ctl configtest

如果你能说明是:

  • 禁止目录列表
  • 禁止访问整个目录
  • 禁止某个子目录
  • 还是 URL 路径

我可以给你更精确的配置示例。

0