瀏覽開源鏡像站(如網易、Ubuntu)時,常見到可直接列出目錄結構的頁面。這其實是 Apache 的「目錄索引」功能。本文將系統說明如何在 Apache 中啟用、禁用目錄瀏覽,並進階示範如何自訂索引頁面的外觀樣式。
httpd.conf(1)目錄層級配置
<Directory /home/www.111cn.net/teddysun> # Options Indexes FollowSymLinks Options FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory>
將 Options Indexes FollowSymLinks 改為 Options FollowSymLinks,即可禁止該目錄顯示列表。
原理: Indexes 指令會在目錄缺少 index.html 時自動產生目錄列表;移除它,Apache 就不會輸出列表。
(2)虛擬主機配置
<VirtualHost *:80> ServerName domain ServerAlias domains DocumentRoot /home/www/teddysun CustomLog /home/www/teddysun/logs/access.log combined DirectoryIndex index.php index.html <Directory /home/www/teddysun> Options +Includes -Indexes AllowOverride All Order Deny,Allow Allow from All </Directory> </VirtualHost>
在 Indexes 前加 - 號(-Indexes)同樣能禁用目錄瀏覽。+ 代表允許,- 代表禁止。
.htaccess 檔案在網站根目錄建立或編輯 .htaccess,加入:
<Files *> Options -Indexes </Files>
同樣以 -Indexes 禁用目錄瀏覽,+Indexes 則啟用。
httpd.conf 開啟索引<Directory /home/www/teddysun> Options Indexes FollowSymLinks IndexStyleSheet "/css/style.css" IndexOptions FancyIndexing HTMLTable ScanHTMLTitles FoldersFirst NameWidth=85 DescriptionWidth=128 IconWidth=16 IconHeight=16 VersionSort Charset=UTF-8 AllowOverride all Order allow,deny Allow from all </Directory>
在 Options 中加入 Indexes 即開啟目錄瀏覽。注意:CentOS 6 透過 yum 安裝的 Apache 預設開啟索引,但 /etc/httpd/conf.d/welcome.conf 中的 -Indexes 會覆蓋根目錄設定,需手動調整。
IndexOptions 參數詳解與樣式自訂FancyIndexing:啟用美化表格樣式HTMLTable:配合 FancyIndexing 產生表格結構ScanHTMLTitles:從 HTML 檔案讀取 <title> 作為描述FoldersFirst:目錄優先於檔案顯示NameWidth=85:檔名欄最大寬度(英文字元)DescriptionWidth=128:描述欄最大寬度IconWidth=16 / IconHeight=16:圖示尺寸(像素)VersionSort:依版本號排序(而非字母順序)Charset=UTF-8:指定字元集其他進階選項如 AddAltClass、IconsAreLinks、IgnoreCase、SuppressDescription 等,請參考 Apache 官方文件。