Splitting Apache vhosts configuration for a Mac

Last Updated On

Foreword

I assume that you have apache web-server installed. You also should be familiar with a basic concept of vhosts* file. If these terms sound unfamiliar to you, please take a look at this article (it describes the configuration for ubuntu/debian, but a very similar concept can be applied to a Mac or Windows).

This post is intended to show how to clean up your mess in vhosts* file. It mostly applicable to a local environment rather than production.

The problem

It’s a very common situation when you need to fix website’s bug, implement a new feature or set-up entire CMS from scratch. In a PHP world more than likely you’ll use PHP/Apache bundle. Each time you set up a new environment you need to add your web-server configuration to vhosts* file. After a certain amount of time, this file can become really gigantic. In my case, it grew up to few hundred lines of code that made it impossible to manage and adjust my existing environment setup.

The solution

  1. Find your Apache configuration file. For Mac built-in apache path will be /etc/apache2/httpd.conf, for Apache installed with brew it will be /usr/local/etc/httpd/httpd.conf. Open it with your favorite editor (nano, vim or another one).
  2. Find a # Virtual hosts line. Below this line, you should see Include directive and path to already existing virtual hosts file. I use Apache installed with brew and for me it was Include /usr/local/etc/httpd/extra/httpd-vhosts.conf. It might be different if you’re using preinstalled version of Apache for Mac.
  3. Add our custom Include directive. Looking ahead, let’s make it even easier to edit by creating it in our home(or child directory) instead of system one. It will save some time, because you’ll able to open it in your favorite text editor without granting root permissions. The rule might look like this:
Include /Users/username/myAwesomeFolder/configurations/my-virtual-hosts/*.conf

It probably is not the best way to name your configuration, but it shows that you’re not limited to pick up a specific name. It represents the following instruction: use all files with .conf extension located under my-virtual-hosts directory as a virtual hosts.

  1. You can start creating your own virtual hosts files. Reboot you Apache when you finish and that’s it!

*vhosts – in this article file name vhosts is used as a general name for Apache Virtual Hosts. Please note, for each operating system name of the file can be different (e.g. for default Mac Apache it’s called httpd-vhosts.conf, on ubuntu server it called as 000-default.conf and default-ssl.conf ).