首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

PHP 環境下訪問 localhost 出現 403 Forbidden 的三種解決方案

     編輯:程式設計綜合問答

問題現象

Apache + PHP 環境,htdocs 目錄下有 `index.html` 和 `test.php`。
訪問 `https://localhost` 正常顯示 `index.html`。
重命名 `index.html` → `index11.html` 後,再訪問 `https://localhost` 報錯:

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

預期應顯示目錄列表(`index11.html` 和 `test.php` 鏈接),但實際被禁止訪問。

根本原因

Apache 默認配置:

  1. DirectoryIndex:指定默認首頁文件,通常為 `index.html`、`index.php`。
  2. Options Indexes:默認關閉目錄瀏覽功能。

當請求目錄 `/` 且無匹配的 DirectoryIndex 文件時,若 `Indexes` 關閉,直接返回 403。

三種解決方案(按推薦程度排序)

方案一:修改 DirectoryIndex 增加自定義首頁文件(推薦)

編輯 `httpd.conf` 或站點配置文件:

<IfModule dir_module>
    DirectoryIndex index.html index.php index11.html
</IfModule>

重啟 Apache。此後訪問 `https://localhost` 會自動查找 `index11.html`。
優點:無安全風險,符合生產環境規範。
缺點:需修改配置文件並重啟服務。

方案二:開啟目錄瀏覽 Options Indexes(開發環境可用)

<Directory "D:/APMServ/www">  
    Options Indexes FollowSymLinks  
    AllowOverride All
    Require all granted
</Directory>

重啟 Apache。訪問目錄無默認文件時,將顯示文件列表。
⚠️ 警告:生產環境嚴禁開啟,會暴露服務器目錄結構、源代碼、配置文件等敏感信息。

方案三:直接訪問具體文件 URL(最簡單)

瀏覽器輸入:https://localhost/index11.html 或 https://localhost/test.php
優點:零配置修改,立即生效。
缺點:不適合作為網站入口,用戶體驗差。

最佳實踐建議

  1. 生產環境:務必設置合適的 `DirectoryIndex`(如 `index.php index.html`),關閉 `Options Indexes`。
  2. 開發環境:可臨時開啟 `Indexes` 方便調試,但养成習慣使用具體文件 URL。
  3. 框架項目:Laravel/ThinkPHP 等框架入口通常是 `public/index.php`,需將 DocumentRoot 指向 `public` 目錄,並設置 `DirectoryIndex index.php`。
  4. .htaccess 覆蓋:若無權修改主配置,可在網站根目錄創建 `.htaccess`:
    DirectoryIndex index11.html index.php index.html
    # Options -Indexes  # 確保關閉目錄瀏覽
    

驗證配置生效

# 檢查語法
apachectl -t  # Linux/Mac
httpd -t      # Windows

# 重啟服務
systemctl restart httpd      # CentOS 7+/RHEL
service apache2 restart      # Ubuntu/Debian
# Windows: 服務管理器或 httpd -k restart
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved