在 Windows 開發環境配置虛擬主機,可實現多專案獨立域名訪問 (如 `project1.local`、`api.local`),避免端口衝突與路徑汙染。本文以 Apache 2.4 為例,步驟清晰可直接落地。
# 找到並取消註釋 (去掉 #)
Include conf/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerName www.mydemo.com
DocumentRoot "D:/mydemo"
<Directory "D:/mydemo">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
# 可選:錯誤/存取日誌分離
ErrorLog "logs/mydemo-error.log"
CustomLog "logs/mydemo-access.log" common
</VirtualHost>
關鍵指令說明
- `ServerName`:匹配的域名
- `DocumentRoot`:網站根目錄 (使用正斜槓或雙反斜槓)
- `AllowOverride All`:允許 `.htaccess` 覆蓋 (Laravel/TP/ThinkPHP 必須)
- `Require all granted`:Apache 2.4 授權語法 (舊版為 `Order allow,deny / Allow from all`)
127.0.0.1 www.mydemo.com
127.0.0.1 api.mydemo.com
::1 www.mydemo.com # IPv6 兼容
mkdir D:\mydemo
echo "<?php phpinfo(); ?>" > D:\mydemo\index.php
| 現象 | 原因 | 解決 |
|---|---|---|
| 403 Forbidden | 目錄權限不足 | 檢查 ` |
| 404 Not Found | DocumentRoot 路徑錯誤 | 確認路徑存在、斜槓方向、大小寫 |
| 域名跳轉到預設站點 | ServerName 不匹配 | 核對 hosts、ServerName 拼寫、清除瀏覽器快取 |
| .htaccess 不生效 | AllowOverride None | 改為 `AllowOverride All` 並重啟 |
| 端口 80 被佔用 | System/IIS/Skype 佔用 | `netstat -ano | findstr :80` 找 PID 終止,或改 Apache 端口 |
<VirtualHost *:80>
ServerName mydemo.com
ServerAlias *.mydemo.com
VirtualDocumentRoot "D:/www/mydemo/%1" # 需 mod_vhost_alias
</VirtualHost>
新增資料夾 `D:/www/mydemo/api` 即可自動對應 `api.mydemo.com`。
<VirtualHost *:80>
ServerName legacy.local
DocumentRoot "D:/legacy"
# 指定 PHP 5.6 模組
<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9056"
</FilesMatch>
</VirtualHost>
<VirtualHost *:80>
ServerName modern.local
DocumentRoot "D:/modern"
# 指定 PHP 8.2 模組
<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9082"
</FilesMatch>
</VirtualHost>
<VirtualHost *:443>
ServerName secure.local
DocumentRoot "D:/secure"
SSLEngine on
SSLCertificateFile "conf/ssl/secure.local.crt"
SSLCertificateKeyFile "conf/ssl/secure.local.key"
</VirtualHost>
生成自簽憑證:`openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout secure.local.key -out secure.local.crt`
提示:Windows 修改 hosts 需管理員權限,建議使用 HostsFileEditor 等圖形工具簡化操作。生產環境請使用 Nginx 反向代理 + 域名解析,勿直接用 Apache 虛擬主機對外服務。