Apache 的 mod_autoindex 模組控制目錄列表顯示。正確配置可避免敏感檔案洩露,或建立美觀的檔案下載站。本文涵蓋禁用、啟用、樣式自定義三大場景。
<Directory /var/www/html>
# 移除 Indexes,保留 FollowSymLinks
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>
原理:Indexes 選項啟用目錄列表;移除即禁用。
<VirtualHost *:80>
DocumentRoot /var/www/site
<Directory /var/www/site>
Options +Includes -Indexes # -Indexes 明確禁用
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
<Files *>
Options -Indexes
</Files>
在網站根目錄建立 .htaccess 並寫入上述內容即可生效(需 AllowOverride Options)。
<Directory /var/www/downloads>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/downloads>
Options Indexes FollowSymLinks
IndexStyleSheet "/css/directory.css" # 相對 DocumentRoot
IndexOptions FancyIndexing HTMLTable FoldersFirst \
NameWidth=80 DescriptionWidth=120 \
IconWidth=16 IconHeight=16 \
VersionSort Charset=UTF-8 \
IgnoreCase
AllowOverride None
Require all granted
</Directory>
| 參數 | 作用 |
|---|---|
| FancyIndexing | 啟用修飾表格模式(而非純文字列表) |
| HTMLTable | 配合 FancyIndexing 產生結構化表格 |
| FoldersFirst | 目錄優先顯示在檔案之前 |
| NameWidth=80 | 檔名欄寬度(字元數) |
| DescriptionWidth=120 | 描述欄寬度 |
| IconWidth/IconHeight | 圖示尺寸(像素) |
| VersionSort | 版本號自然排序(如 1.9 < 1.10) |
| Charset=UTF-8 | 指定輸出編碼,避免中文亂碼 |
| IgnoreCase | 排序忽略大小寫 |
| SuppressDescription | 隱藏描述欄 |
| SuppressIcon | 隱藏圖示 |
| SuppressSize | 隱藏檔案大小 |
| TrackModified | 回傳 Last-Modified/ETag,利用快取 |
/* 目錄索引美化 */
body { font-family: 'Microsoft YaHei', sans-serif; margin: 20px; background: #f9f9f9; }
h1 { color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }
table { width: 100%; border-collapse: collapse; background: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; }
th { background: #4CAF50; color: white; font-weight: 500; }
tr:hover { background: #f5f5f5; }
a { color: #2196F3; text-decoration: none; }
a:hover { text-decoration: underline; }
.icon { vertical-align: middle; margin-right: 8px; }
.size, .date { color: #666; font-size: 0.9em; }
.folder { font-weight: bold; }
/etc/httpd/conf.d/welcome.conf 中含 Options -Indexes,需註釋或刪除該檔案。755,檔案 644,Apache 使用者(apache/www-data)需可讀取。合理配置目錄索引,既能滿足檔案分享需求,又能守住資安底線。