Setting up local development domain with Apache vhosts

Apr 06, 2013

When working with Apache on web projects, there is a convenient way to set up access to your project through a local domain. For example, if you are working on fooproject that will be live on fooproject.com, you can use fooproject.dev domain for local development.

Several steps are required in order to configure your system:

  1. Create vhosts.conf to hold your configuration
  2. Include created file in Apache configuration
  3. Add hosts file entry

Creating VirtualHost configuration

Create vhosts.conf (or any name you like) file that will hold the configuration for the project you are working on. I prefer to keep configuration for all projects in one file, located above my projects directory, but you can also have one vhosts.conf per project. Here is the minimum configuration:

<VirtualHost fooproject.dev:80>
  ServerName fooproject.dev
  DocumentRoot "/path/to/fooproject/public"
  ErrorLog "/path/to/log/directory/fooproject.dev-error.log"

  <Directory "/path/to/fooproject/public">
    Allow from all
    AllowOverride All
    Require all granted
    Options +Indexes
  </Directory>
</VirtualHost>
Note: In order to add a server alias (e.g. www.fooproject.dev), you must add ServerAlias www.fooproject.dev directive in your <VirtualHost> entry, and 127.0.0.1 www.fooproject.dev entry in the hosts file. For more information, visit the official Apache virtual host documentation.

Next step is to include your vhosts.conf file in the Apache's httpd-vhosts.conf:

apache\conf\extra\httpd-vhosts.conf

...
include "/path/to/my/vhosts.conf"
Note: You can directly paste your settings in httpd-vhosts.conf file, but if you decide to upgrade Apache in the future, you might overwrite this file on accident. It's best to keep things modular.

A restart of the server is required in order to load the new configuration. In order to check for errors, use the command line utility to start the server - it will show errors in the console.

Editing the hosts file

In order for you browser to resolve the local domain to your local server, you need to add an entry in the hosts file:

...
127.0.0.1 fooproject.dev
  • On Windows: C:\Windows\System32\drivers\etc\hosts
  • On Linux: /etc/hosts
Note: Some browsers (e.g. Chrome) require that you put a backslash character at the end of the address for .dev domain, else they will perform a search query. In this case, use a backslash: fooproject.dev/.

After setting everything up, your project should be available at fooproject.dev/ and served from the directory set in the DocumentRoot directive.

comments powered by Disqus