Apache 安裝後預設文件根目錄通常位於 htdocs,實際部署時常需調整至專案目錄或設定多站點虛擬主機。本文詳細說明修改預設目錄步驟、虛擬主機配置、權限設定與常見錯誤排查,適用於 Windows/Linux 環境。
apache/conf/httpd.conf 或 apache2/conf/httpd.conf/etc/apache2/httpd.conf 或 /etc/httpd/conf/httpd.conf/etc/apache2/httpd.conf搜尋 DocumentRoot(約第 250 行),修改路徑:
# 原始
DocumentRoot "C:/wamp/bin/apache/Apache2.2.21/htdocs"
# 修改為你的專案目錄(使用正斜線,雙引號不可少)
DocumentRoot "D:/MyProjects/PublicWeb"
緊接著搜尋 <Directory "...">(約第 280 行),同步修改:
# 原始
<Directory "C:/wamp/bin/apache/Apache2.2.21/htdocs">
# 修改
<Directory "D:/MyProjects/PublicWeb">
在同一 <Directory> 區塊內,確保包含:
<Directory "D:/MyProjects/PublicWeb">
Options Indexes FollowSymLinks
AllowOverride All # 允許 .htaccess 覆寫(需模組 mod_rewrite)
Require all granted # Apache 2.4+ 語法,允許所有存取
</Directory>
Apache 2.2 舊語法: Order allow,deny / Allow from all
# Windows (管理員 CMD)
httpd -k restart
# Linux systemd
sudo systemctl restart apache2 # Ubuntu/Debian
sudo systemctl restart httpd # CentOS/RHEL
修改預設目錄僅適合單一站點。生產環境強烈建議使用 虛擬主機,隔離專案、綁定域名、獨立日誌。
在 httpd.conf 確認以下行未被註解:
LoadModule vhost_alias_module modules/mod_vhost_alias.so
# 包含獨立虛擬主機配置檔(推薦)
Include conf/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
DocumentRoot "D:/MyProjects/Example/Public"
<Directory "D:/MyProjects/Example/Public">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog "logs/example-error.log"
CustomLog "logs/example-access.log" common
</VirtualHost>
<VirtualHost *:80>
ServerName api.example.com
DocumentRoot "D:/MyProjects/Api/Public"
# ... 同樣的 Directory 設定
</VirtualHost>
# Windows: C:\Windows\System32\drivers\etc\hosts
# Linux/macOS: /etc/hosts
127.0.0.1 www.example.com
127.0.0.1 api.example.com
| 現象 | 可能原因 | 解決方法 |
|---|---|---|
| 403 Forbidden | Directory 區塊缺少 Require all granted / 權限不足 | 檢查 Directory 設定、資料夾權限 755、檔案 644、SELinux contexts |
| 404 Not Found | DocumentRoot 路徑錯誤、拼寫大小寫(Linux 區分大小寫) | 用實際路徑測試 ls -la /path,確認 Apache 進程使用者可讀取 |
| .htaccess 不生效 | AllowOverride None / 未載入 mod_rewrite | 設定 AllowOverride All、確認 LoadModule rewrite_module |
| 重啟失敗 | 語法錯誤、端口佔用 | 執行 apachectl -t 或 httpd -t 檢查語法;netstat -an | grep :80 檢查端口 |
/ 或雙反斜線 \\,避免單反斜線被視為跳脫字元。SYSTEM 或指定使用者執行,確保該使用者對目標資料夾有「讀取/執行」權限。//server/share 並設定服務登入身分。ServerTokens Prod、ServerSignature OffOptions -Indexes(生產環境)AllowOverride AuthConfig FileInfo Limit 按需開放掌握 Apache 目錄與虛擬主機配置,是佈署 PHP/靜態站點的基礎功力。建議採用「一站一虛擬主機、獨立日誌、獨立目錄」的規範結構,便於維護、擴展與故障隔離。