在 Windows 本地開發環境配置多個虛擬主機 (如 www.site1.local, api.site2.local) 需修改三個檔案:系統 hosts 解析域名、Apache 主配置 httpd.conf 載入虛擬主機模組、虛擬主機配置 httpd-vhosts.conf 定義站點。本文提供標準化步驟與常見坑點。
路徑:C:\Windows\System32\drivers\etc\hosts (需管理員權限編輯)
127.0.0.1 localhost
127.0.0.1 www.site1.local
127.0.0.1 api.site2.local
127.0.0.1 admin.site3.local
提示: 使用 notepad C:\Windows\System32\drivers\etc\hosts 在「以管理員身分執行」的命令提示字元中開啟。
路徑:Apache24\conf\httpd.conf
mod_vhost_alias (可選,動態虛擬主機用):LoadModule vhost_alias_module modules/mod_vhost_alias.sohttpd-vhosts.conf 匯入 (去掉行首 #):Include conf/extra/httpd-vhosts.confServerName 已設定 (避免啟動警告):ServerName localhost:80路徑:Apache24\conf\extra\httpd-vhosts.conf
ServerName www.site1.local
DocumentRoot "D:/www/site1/public"
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
ErrorLog "logs/site1-error.log"
CustomLog "logs/site1-access.log" common
ServerName api.site2.local
DocumentRoot "D:/www/site2/api"
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# API 專用:關閉目錄列表、啟用 CORS 模組等
ServerName admin.site3.local
DocumentRoot "D:/www/site3/admin"
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# 命令列
httpd -k restart
# 或服務管理器重啟 Apache2.4 服務
瀏覽器訪問 https://www.site1.local 應正確顯示對應站點。
| 現象 | 可能原因 | 解決 |
|---|---|---|
| 訪問域名顯示預設頁面 (It works!) | VirtualHost DocumentRoot 路徑錯誤或 | 檢查路徑大小寫、Require all granted、重啟 Apache |
| 403 Forbidden | Require all granted | Apache 2.4 預設拒絕所有,必須顯式授權 |
| 修改 hosts 不生效 | DNS 快取 | ipconfig /flushdns、瀏覽器清除快取、ping 域名確認解析 |
| Apache 啟動失敗 | 語法錯誤、端口被佔用 | httpd -t 檢查語法、netstat -ano | findstr :80 查端口佔用 |
| PHP 不執行 (顯示原始碼) | 未載入 php_module 或未設定 AddHandler | 確認 LoadModule php_module、AddHandler application/x-httpd-php .php、PHPIniDir |
ServerName dev.local
ServerAlias *.dev.local
VirtualDocumentRoot "D:/www/%-2+/public"
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
配合 hosts:127.0.0.1 *.dev.local (需使用 泛域名 hosts 工具 或本地 DNS 如 dnsmasq)。