How to set up virtual hosts in apache on Mac OS.
What is Virtual Host
Virtual Host is used to serve multiple websites from single server. Virtual host used to enclose a group of directives that will apply only to a particular virtual host.
How to Set Up Virtual Hosts in Apache on Mac OS
Let’s set up our virtual host. To start with, Open httpd.conf file in your editor. I am using terminal with vim editor.
If you are not familiar with vim editor then check my previous tutorial on Vim editor guide.
1 |
sudo vim /etc/apache2/httpd.conf |
Search for httpd-vhosts.conf and uncomment this line. Search and replace in Vim editor.
1 2 3 |
// Uncomment this line. Include /private/etc/apache2/extra/httpd-vhosts.conf |
Now open httpd-vhosts.conf file in vim (or any editor you prefer).
1 |
sudo vim /private/etc/apache2/extra/httpd-vhosts.conf |
Directives and their Meaning used in Virtual Host
DocumentRoot – It specify which file to serve by Apache for a given request. In my case i have pointed my new project directory (/Library/WebServer/Documents/first_project/ ).
ServerName – ServerName is used to uniquely identify a virtual host when using name based virtual hosts.
ServerAlias – It sets the alternate name for a host. It may include wildcards as well (ServerName *.local.com) .
AllowOverride All – This directive allow .htaccess file directives to apply on your project. If you don’t want to apply .htaccess directives then set AllowOverride None.
Complete explanation of htaccess is explained in my previous htaccess tutorials.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<VirtualHost *:80> DocumentRoot /Library/WebServer/Documents/first_project/ ServerName local.com ServerAlias www.local.com ErrorLog "/private/var/log/apache2/local.com-error_log" CustomLog "/private/var/log/apache2/local.com-access_log" common ServerAdmin admin@local.com <Directory "/Library/WebServer/Documents/first_project/"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost> |
Now we have set up our virtual host. Let’s map ip address to domain name in hosts file.
1 |
sudo vim /etc/hosts |
Add following entry in hosts file.
1 |
127.0.0.1 local.com www.local.com |
Now everything is done. Let’s restart apache server.
1 |
sudo apachectl restart |
Reference Link