Last Updated: February 25, 2016
·
2.207K
· pmaoui

Create dynamic virtual hosts with Apache2

It consists to create a directory named www.mywebsite.local and having access directly through your browser at this URL. Consider using it in a development environment.

First, install vhost_alias module for apache2.

sudo a2enmod vhost_alias

Then put in /etc/apache2/sites-available/vhost.conf :

<VirtualHost *:80>
  UseCanonicalName Off
  LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
  CustomLog /var/log/apache2/vhosts.access.log vcommon
  VirtualDocumentRoot /home/user/Public/%0/

<Directory /home/user/Public>
  Require all granted
  Options -Indexes +FollowSymLinks +ExecCGI
  AllowOverride All
</Directory>

</VirtualHost>

Replace user by your linux account

Then, activate this dynamic vhost :

sudo a2ensite vhost && sudo service apache2 reload

The last thing you need to do is editing your host file to bind www.mywebsite.local to 127.0.0.1.

Just add in /etc/hosts this line :

127.0.0.1   www.mywebsite.local

To test your setup, create in /home/user/Public/www.mywebsite.local/index.php with on it :

<?php echo "Hello World"; ?>

Then try to access to www.mywebsite.local. "Hello World" should appears.