How to set up Virtual Hosts on Mac

當你在開發的時候,可能會透過路徑去呼叫檔案,但是這樣的url的長度可能會滿長一串的,此時你可以透過設定Virtual Hosts,就可以輸入較短的url呼叫到同一筆檔案。

一、先打開httpd.conf

sudo vi /etc/apache2/httpd.conf

二、尋找Virtual hosts,將Include前的#移除

# Virtual hosts
# Include /private/etc/apache2/extra/httpd-vhosts.conf

三、打開httpd-vhosts.conf

sudo vim /etc/apache2/extra/httpd-vhosts.conf

開啟後應該可以看到檔案中有預設的設定檔可以查看,預設的設定如下:

<VirtualHost *:80>
ServerAdmin webmaster@dummy-host.example.com
DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
ServerName dummy-host.example.com
ServerAlias www.dummy-host.example.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>

四、新增VirtualHost資訊(參考設定檔案修改)

<VirtualHost *:80>
DocumentRoot "/Users/username/Sites/project"
ServerName local.project
</VirtualHost>

五、開啟etc/hosts

sudo vim /etc/hosts

六、加入IP及要指向的位址名稱

127.0.0.1 project.local

七、重啟apache

sudo apachectl -k restart

以上步驟設定好就完成了!

Show your support

Clapping shows how much you appreciated Elsa Wang’s story.