OverDocs

Creating virtual host Edit on GitHub In category: Apache

Virtual hosts #vhosts

Using virtual hosts (vhosts) in Apache you can map specified directory to the domain name. It is not only needed when you want to serve more than one domain on the server, but could be also useful during local development.

In order to define new virtual host, add following code to your Apache config. This is the simplest form, there are more directives you can use, but below one will work.

<VirtualHost *:80>
    DocumentRoot [path to the site]
    ServerName domain.tld # replace it by your own value
</VirtualHost>

When doing local development, you need to map specified domain name to respective IP address, usually 127.0.0.1. Theoretically you can set up your own DNS server, but it's unneeded complication, unless you don't use advanced features, such as domain wildcards etc.

Open the file /etc/hots (or X:\Windows\system32\drivers\etc\hosts on Windows) and add a following entry to it:

127.0.0.1 domain.tld

Restart Apache process if it was running and you should be able to open domain.tld in your browser.

Note

After you add your first virtual host, you will probably encounter a problem with accessing http://localhost. The simplest way to fix it is to add following entry before your custom hosts:

<VirtualHost *:80>
    DocumentRoot [path to htdocs folder]
    ServerName localhost
</VirtualHost>

localhost is mapped to 127.0.0.1 automatically, you don't need to add anything to hosts file.

Learn more #learn-more

Comments #comments