Apache 預設開啟 `Options Indexes`,當目錄無索引檔 (index.html/index.php) 時自動列出目錄結構,**洩露檔案結構、敏感備份檔、原始碼**,屬嚴重資安風險。本文說明全域與單站點/目錄級禁用方法。
`mod_autoindex` 模組處理目錄列表。`Options Indexes` 開啟列表功能;**移除 `Indexes` 或加前綴 `-` (即 `Options -Indexes`)** 即可禁用。
/etc/httpd/conf/httpd.conf/etc/apache2/apache2.conf 或 /etc/apache2/sites-available/000-default.conf (虛擬主機內)
# 找到 或對應 DocumentRoot 區塊
Options FollowSymLinks # 刪除 Indexes,或顯式寫 -Indexes
AllowOverride None
Require all granted
關鍵: `Options FollowSymLinks` 保留符號連結跟隨功能 (常需);**移除 `Indexes`**。
# 在網站根目錄或需保護的子目錄建立 .htaccess
vim /var/www/html/.htaccess
# 內容:
Options -Indexes
# 或顯式關閉
# Options -Indexes -Includes -ExecCGI
立即生效,無需重啟 Apache。
mkdir -p /var/www/html/testdir && echo "secret" > /var/www/html/testdir/secret.txthttps://ServerIP/testdir/
# httpd.conf / apache2.conf / .htaccess
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
# /var/www/html/errors/403.html
403 Forbidden
403 - 禁止訪問
目錄瀏覽已被禁用。如有疑問請聯繫管理員。
| 配置 | 指令 | 作用 |
|---|---|---|
| 隱藏 Apache 版本/OS | ServerTokens Prod ServerSignature Off | 減少資訊洩露 |
| 禁用 .htaccess (若掌握主配置權) | AllowOverride None | 提升效能、避免配置分散 |
| 限制 HTTP 方法 | 防 WebDAV/DEBUG 等危險方法 | |
| 禁用 TRACE 方法 | TraceEnable Off | 防 XST (Cross-Site Tracing) |
| 安全標頭 | Header always set X-Frame-Options "SAMEORIGIN" Header always set X-Content-Type-Options "nosniff" Header always set Referrer-Policy "strict-origin-when-cross-origin" | 需啟用 mod_headers |
# Nginx 預設不開啟目錄瀏覽,需顯式開啟 autoindex on;
# 禁用即移除或設為 off
location / {
autoindex off; # 預設即為 off
}