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

Apache 禁止目錄瀏覽 403 配置指南

     編輯:PHP 相關知識

為防止敏感文件洩露,生產環境必須禁用 Apache 目錄索引功能。本文詳解 httpd.conf 配置修改、.htaccess 替代方案、虛擬主機隔離配置及驗證方法。

核心配置:httpd.conf

方法一:全局禁用 (推薦)

# 找到主 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 替代方案 (無權修改主配置)

# 放在網站根目錄 .htaccess
Options -Indexes

# 或完全禁止訪問 (返回 403)
# Deny from all  # Apache 2.2
# Require all denied  # Apache 2.4+

前提:對應目錄 AllowOverride Options 或 AllowOverride All。

驗證方法

  1. 重啟 Apache:sudo systemctl restart apache2 / httpd -k restart
  2. 訪問無索引文件的目錄:https://your-domain.com/subdir/
  3. 預期結果:403 Forbidden
    Forbidden
    You don't have permission to access /subdir/ on this server.
  4. 正常文件訪問不受影響:https://your-domain.com/index.php

常見問題排查

現象原因解決
修改後仍顯示目錄配置未生效檢查語法 apachectl -t、確認重啟、檢查是否被後載入配置覆蓋
所有頁面 403Require all denied 錯誤檢查 Require all granted 在目錄塊中
.htaccess 不生效AllowOverride None改為 AllowOverride Options 或 All
子目錄仍可瀏覽父目錄配置未遞歸Apache 配置默認遞歸,檢查子目錄是否有獨立 Options +Indexes

安全加固建議

  1. 隱藏版本信息:ServerTokens Prod、ServerSignature Off
  2. 禁用不必要模塊:a2dismod autoindex (直接卸載模塊)
  3. 敏感文件保護:
    <FilesMatch "^\.">
        Require all denied
    </FilesMatch>
    <FilesMatch "\.(env|ini|log|bak|sql)$">
        Require all denied
    </FilesMatch>
  4. 啟用 ModSecurity WAF:應用層防護

Nginx 對比配置

# Nginx 禁用目錄瀏覽 (默認關閉)
location / {
    autoindex off;  # 顯式關閉
    # try_files $uri $uri/ =404;  # 無索引文件返回 404
}

禁用目錄瀏覽是 Web 服務器安全基線配置,務必在所有生產環境執行並驗證。

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