Christoffer Kjølbæk I have a blog, therefore I am…

8May/090

Virtual sub-domains on localhost for development

Using Apache and mod_vhost_alias, it is possible to have one configuration file for all you development home-pages. But notice before you start, that $_SERVER["DOCUMENT_ROOT"] will NOT work with this hack!

First step is to enable mod_vhost_alias:

sudo a2enmod vhost_alias

Next you have to make a config file for apache. I only use this setup, and have no other virtual hosts, so I just uses the default config file:

sudo gedit /etc/apache2/sites-enabled/000-default

and make it something like:

<VirtualHost *:80>
   ServerName localhost
   ServerAlias *.localhost

   VirtualDocumentRoot /var/www/htdocs/%1/

   <directory /var/www/>
      AllowOverride AuthConfig Options FileInfo Limit
      Options MultiViews SymlinksIfOwnerMatch
      Order allow,deny
      Allow from all
   </Directory>

   ErrorLog /var/log/apache2/error.log
   LogLevel warn
</virtualhost>

The important part is that there is not DocumentRoot, but instead the line:

VirtualDocumentRoot /var/www/htdocs/%1/

%1 means "the first part" of the domain, so if the domain is customer1.localhost the document root will be /var/www/htdocs/customer1/. There is different settings for this, which can be seen in the Apache doc.

Remember to restart apache:

sudo /etc/init.d/apache2 restart

Now you just have to create all the directories in /var/www/htdocs/ as you like, and add the corresponding sub-domains in the host file:

sudo gedit /etc/hosts

and add the sub-domains

127.0.1.1 customer1.localhost
127.0.1.1 customer2.localhost
127.0.1.1 customer3.localhost

Have fun :)

Update: index page
Creating the directory /var/www/htdocs/localhost/ with the below code in index.php, it is possible to make an index page of all pages.

<?
$dir_handle = @opendir("../");

while ($file = readdir($dir_handle)) {
if($file!="." && $file!=".." && $file!="localhost") echo "<a href='http://$file.localhost'>http://$file.localhost<br />";
}

closedir($dir_handle);

?>

Kommentarer (0) Trackbacks (0)

Ingen kommentarer endnu.


Læg en kommentar


Ingen trackbacks endnu.