Virtual Host คืออะไร ?
Virtual Host คือ การทำให้ Server เครื่องเดียวสามารถให้บริการได้มากกว่า 1 เว็บไซต์ ซึ่งโดยปกติสามารถให้บริการได้เพียงเว็บไซต์เดียว การทำ Virtual Host สามารถทำได้หลายวิธี ดังนี้
- Name-based Virtual Host - การอ้างอิงโดยใช้ Domain Name หรือ Host Name
- Port-based Virtual Host - การอ้างอิงโดยใช้ Port Number
- IP-based Virutal Host - การอ้างอิงโดยใช้ IP Address
- การใช้ทั้ง Port-based ร่วมกับ IP-based
- การใช้ทั้ง Name-based ร่วมกับ IP-based
ซึ่งบทความนี้จะแนะนำและแสดงวิธีการทำแบบ Name-based Virtual Host ดังภาพด้านล่าง
เริ่มต้นการทำ Virtual Host แบบ Step By Step
การทำ Virtual Host บน Apache ในระบบปฏิบัติการ MAC OSX 10.10, 10.9 และ OSX 10.8 ต้องแก้ไขไฟล์ดังนี้
- httpd.conf
- httpd-vhosts.conf
- hosts
ขั้นตอนที่ 1 แก้ไข httpd.conf
ทำการแก้ไข httpd.conf ด้วยคำสั่ง
sudo nano /etc/apache2/httpd.conf
หาส่วนของการกำหนดค่า Virtual Hosts แก้ไขเพื่อเปิดใช้งาน Virtual Hosts ตามด้านล่าง
# Virtual hosts
Include /private/etc/apache2/extra/httpd-vhosts.conf
*เมื่อแก้ไขตรงนี้ จะทำให้ Apache เมื่อเริ่มต้นทำงานจะไปอ่านค่าเกี่ยวกับ Virtual Hosts ที่ไฟล์ httpd-vhosts.conf
ขั้นตอนที่ 2 แก้ไข httpd-vhosts.conf
ทำการแก้ไข httpd-vhosts.conf ด้วยคำสั่ง
sudo nano /etc/apache2/extra/httpd-vhosts.conf
กำหนด Virtual Host ของ localhost เพื่อให้สามารถใช้ localhost ได้เหมือนเดิม
<VirtualHost *:80>
ServerName localhost
DocumentRoot /Library/WebServer/Documents/
</VirtualHost>
ต่อมาทำการเพิ่มชื่อ Domain Name หรือ Host Name เพื่ออ้างอิงไปยัง Path ที่เก็บเว็บไซต์ที่ต้องการและกำหนดสิทธิ์การเข้าถึง
<VirtualHost *:80>
ServerName share.olanlab.com
DocumentRoot "/Users/username/Sites/share"
<Directory "/Users/username/Sites/share">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
ตัวอย่างด้านบน
Path ที่เก็บเว็บไซต์เป็น - Users/username/Sites/share
Domain Name เป็น - share.olanlab.com
ขั้นตอนที่ 3 แก้ไข hosts
ทำการแก้ไข hosts ด้วยคำสั่ง
sudo nano /etc/hosts
เปิดไฟล์ขึ้นมาทำการเพิ่ม Host Name และ IP Address เพื่อให้เครื่องของเรารู้จักชื่อ Host Name นี้ว่าจะต้องไปที่ IP Adress อะไร
127.0.0.1 localhost
127.0.0.1 share.olanlab.com
*ไฟล์ hosts ทำหน้าที่เก็บข้อมูล Host Name กับ IP Address ที่ตรงกัน
ขั้นตอนที่ 4 ทำการ Restart Apache
ขั้นตอนสุดท้ายคือการ Restart Apache เพื่อให้ Apache ทำการโหลดค่าที่เรากำหนดใน httpd-vhosts.conf ใหม่ด้วยคำสั่ง
sudo apachectl restart
เท่านี้ก็สามารถใช้ Virtual Host บน Apache ในระบบปฏิบัติการ MAC OSX 10.10, 10.9 และ MAC OSX 10.8 ได้แล้วครับ