在本機開發環境配置虛擬主機,可模擬真實域名存取,方便多專案並行開發。以下以 Windows + WAMP 為例,Linux/Mac 原理相同。
打開 httpd.conf,找到並取消註解:
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
編輯 C:\Windows\System32\drivers\etc\hosts(需管理員權限):
127.0.0.1 myproject.local
127.0.0.1 api.myproject.local
建議使用 .local 或 .test 結尾,避免與真實域名衝突。
確保啟用 NameVirtualHost:
NameVirtualHost *:80
新增虛擬主機區塊:
<VirtualHost *:80>
ServerAdmin admin@myproject.local
DocumentRoot "C:/wamp/www/myproject/public"
ServerName myproject.local
ServerAlias www.myproject.local
ErrorLog "logs/myproject-error.log"
CustomLog "logs/myproject-access.log" common
<Directory "C:/wamp/www/myproject/public">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
若仍需 https://localhost 存取原有專案,需額外定義:
<VirtualHost *:80>
ServerName localhost
DocumentRoot "C:/wamp/www"
<Directory "C:/wamp/www">
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
並在 hosts 加入 127.0.0.1 localhost。
<Directory> 區塊的 Require all grantedipconfig /flushdns)ServerAlias *.myproject.local
搭配 dnsmasq 可實現自動泛域名解析,適合多租戶 SaaS 開發。