萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Apache 403 Forbidden 錯誤徹底解決:Directory 權限配置詳解

錯誤現象

Forbidden
You don't have permission to access / on this server.

本地 https://localhost/test.php 正常,但用內網 IP https://10.10.50.195/test.php 訪問報 403。典型原因:Apache httpd.conf 中 Directory 指令默認拒絕非本地訪問。

核心修復:修改 httpd.conf 兩處 Directory 配置

1. 根目錄權限 <Directory />

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    # Deny from all        # 註釋掉拒絕所有
    Allow from all         # 允許所有來源訪問
    Satisfy all
</Directory>

2. 站點根目錄權限 <Directory "D:/Wamp5/www">

<Directory "D:/Wamp5/www">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order Deny,Allow
    # Deny from all        # 註釋掉
    # Allow from 127.0.0.1 # 註釋掉僅本地
    Allow from all         # 允許所有 IP
</Directory>

關鍵點: Apache 2.2 使用 Order Deny,Allow + Allow from all;Apache 2.4+ 改用 Require all granted。請根據安裝版本選擇語法。

版本差異對照表

指令Apache 2.2Apache 2.4+
允許所有Order allow,deny
Allow from all
Require all granted
拒絕所有Order deny,allow
Deny from all
Require all denied
允許特定 IPOrder deny,allow
Allow from 192.168.1.100
Require ip 192.168.1.100
允許特定域名Allow from example.comRequire host example.com
混合認證Satisfy any/all<RequireAny> / <RequireAll>

WAMP/XAMPP/自編譯環境定位配置文件

  • WAMP: 左鍵托盤圖標 → Apache → httpd.conf(或 httpd-vhosts.conf 虛擬主機配置)。
  • XAMPP: C:\xampp\apache\conf\httpd.conf 及 extra\httpd-vhosts.conf。
  • Linux 系統安裝: /etc/httpd/conf/httpd.conf (RHEL/CentOS) 或 /etc/apache2/apache2.conf (Debian/Ubuntu),站點配置在 sites-available/。

修改後生效步驟

  1. 保存 httpd.conf。
  2. 重啟 Apache 服務:
    • Windows: 服務管理器 (services.msc) 重啟 wampapache64 / Apache2.4;或命令行 httpd -k restart。
    • Linux: systemctl restart httpd / systemctl restart apache2。
  3. 瀏覽器清除緩存,再次用 IP 訪問驗證。

進階:僅允許內網訪問(更安全)

<Directory "D:/wwwroot">
    Options Indexes FollowSymLinks
    AllowOverride All
    # Apache 2.2
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
    Allow from 10.0.0.0/8
    Allow from 192.168.0.0/16
    Allow from 172.16.0.0/12
    # Apache 2.4
    # Require ip 127.0.0.1 10.0.0.0/8 192.168.0.0/16 172.16.0.0/12
</Directory>

排查清單(修改配置後仍 403)

  1. 確認修改的是生效的配置文件(apachectl -t -D DUMP_INCLUDES 查看加載順序)。
  2. 檢查 .htaccess 是否覆蓋了目錄權限(AllowOverride All 允許覆蓋)。
  3. SELinux (CentOS/RHEL):setsebool -P httpd_can_network_connect 1 或臨時 setenforce 0 測試。
  4. 文件系統權限:Apache 運行用戶 (www-data/daemon/apache) 需對目錄有 rx 權限,對文件有 r 權限。chmod -R 755 /var/www/html。
  5. 虛擬主機配置 <VirtualHost> 內是否有獨立 <Directory> 覆蓋全局設置。
copyright © 萬盛學電腦網 all rights reserved