首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Apache 目錄索引(目錄瀏覽)啟用、禁用與樣式自定義完整指南

     編輯:PHP 相關知識

Apache 的 mod_autoindex 模組控制目錄列表顯示。正確配置可避免敏感檔案洩露,或建立美觀的檔案下載站。本文涵蓋禁用、啟用、樣式自定義三大場景。

一、禁用目錄索引(安全預設)

方法 1:修改 httpd.conf / apache2.conf

<Directory /var/www/html>
    # 移除 Indexes,保留 FollowSymLinks
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

原理:Indexes 選項啟用目錄列表;移除即禁用。

方法 2:虛擬主機配置中禁用

<VirtualHost *:80>
    DocumentRoot /var/www/site
    <Directory /var/www/site>
        Options +Includes -Indexes   # -Indexes 明確禁用
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

方法 3:.htaccess(無主機存取權限時)

<Files *>
    Options -Indexes
</Files>

在網站根目錄建立 .htaccess 並寫入上述內容即可生效(需 AllowOverride Options)。

二、啟用並自定義目錄索引樣式

1. 基本啟用

<Directory /var/www/downloads>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

2. 自定義 CSS 樣式(FancyIndexing)

<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>

3. IndexOptions 關鍵參數說明

參數作用
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,利用快取

4. 自定義 CSS 範例(/css/directory.css)

/* 目錄索引美化 */
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; }

三、常見問題

  • CentOS/RHEL 預設歡迎頁阻擋:/etc/httpd/conf.d/welcome.conf 中含 Options -Indexes,需註釋或刪除該檔案。
  • 權限不足:目錄需 755,檔案 644,Apache 使用者(apache/www-data)需可讀取。
  • 大量檔案效能:超過數千檔案時目錄列表生成緩慢,建議啟用快取或改用程式化列表(PHP/Node.js)。

合理配置目錄索引,既能滿足檔案分享需求,又能守住資安底線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved