為防止敏感文件洩露,生產環境必須禁用 Apache 目錄索引功能。本文詳解 httpd.conf 配置修改、.htaccess 替代方案、虛擬主機隔離配置及驗證方法。
# 找到主 Directory 塊
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
# 修改為
<Directory />
Options FollowSymLinks # 移除 Indexes
AllowOverride None
Require all granted
</Directory>
關鍵點:移除 Indexes 選項即可禁用目錄列表。
<Directory "/var/www/html">
Options -Indexes # 明確禁用 (前綴 - 表示移除)
AllowOverride All
Require all granted
</Directory>
<VirtualHost *:80>
DocumentRoot /var/www/site1
ServerName site1.com
<Directory /var/www/site1>
Options -Indexes
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
# 放在網站根目錄 .htaccess
Options -Indexes
# 或完全禁止訪問 (返回 403)
# Deny from all # Apache 2.2
# Require all denied # Apache 2.4+
前提:對應目錄 AllowOverride Options 或 AllowOverride All。
sudo systemctl restart apache2 / httpd -k restarthttps://your-domain.com/subdir/Forbidden
You don't have permission to access /subdir/ on this server.
https://your-domain.com/index.php| 現象 | 原因 | 解決 |
|---|---|---|
| 修改後仍顯示目錄 | 配置未生效 | 檢查語法 apachectl -t、確認重啟、檢查是否被後載入配置覆蓋 |
| 所有頁面 403 | Require all denied 錯誤 | 檢查 Require all granted 在目錄塊中 |
| .htaccess 不生效 | AllowOverride None | 改為 AllowOverride Options 或 All |
| 子目錄仍可瀏覽 | 父目錄配置未遞歸 | Apache 配置默認遞歸,檢查子目錄是否有獨立 Options +Indexes |
ServerTokens Prod、ServerSignature Offa2dismod autoindex (直接卸載模塊)<FilesMatch "^\.">
Require all denied
</FilesMatch>
<FilesMatch "\.(env|ini|log|bak|sql)$">
Require all denied
</FilesMatch>
# Nginx 禁用目錄瀏覽 (默認關閉)
location / {
autoindex off; # 顯式關閉
# try_files $uri $uri/ =404; # 無索引文件返回 404
}
禁用目錄瀏覽是 Web 服務器安全基線配置,務必在所有生產環境執行並驗證。