Apache VirtualHosts on Internal Network (No DNS)

It’s quite common for web engineers to develop applications on either a local machine, or a server running on the local network. In many situations one does not have the luxury of a domain name service to base everything off of, and it becomes a matter of using the IP address or an internal host file.

For example, I have an internal server that we do most of our development on and we’ve typically placed everything in the default htdocs directory. That tends to be a problem if we’re working on a pre-existing application that was designed to work only from the root level.

In the following steps I’ll describe setting up a virtual host and how to trick your computer into simulating the domain service.

On your remote machine, edit the apache configuration file (locations may vary). By default, it’s typically found in /usr/local/apache2/conf/httpd.conf.

Search for and uncomment the following section:

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Save the file, and then proceed with editing that include file:

vi /usr/local/apache2/conf/extra/httpd-vhosts.conf

The first step is to create a new virtual host. In the following example, we tell apache that any traffic to this server under the domain name “myfakedomain” should be treated as a request for the files under the new DocumentRoot.

The second virtual host describes the original default server configuration. Paths to folders will vary depending on how apache was originally installed and configured.

<virtualhost *:80>
DocumentRoot "/usr/local/apache2/virt/myfakedomain.com"
ServerName myfakedomain.com
</virtualhost>

<virtualhost *:80>
DocumentRoot "/usr/local/apache2/htdocs"
ServerName localhost
</virtualhost>

After saving your changes, you need to edit the hosts file on the remote machine so that when apache restarts, it doesn’t go looking for the real domain name you’ve provided.

Using either root or a sudo account, edit the hosts file:

/etc/hosts

Add a new line that follows the pattern of the existing examples:

127.0.0.1 myfakedomain.com

Then, restart apache:

/usr/local/apache2/bin/apachectl restart

You also need to edit your local hosts file so that your system redirects any traffic to myfakedomain.com to your network server, rather than trying to search the internet for it.

For Mac OS X 10.5 users, you may do this by using the same method as the remote server:

sudo vi /etc/hosts
127.0.0.1 myfakedomain.com

Save the file and then flush out any cache:

dscacheutil -flushcache

Open your web browser and try to access myfakedomain.com. You should see whatever was in your apache document root.

Leave a Reply