Home > HowTo's > Easy Apache VirtualHost config

Easy Apache VirtualHost config

March 15th, 2009 Leave a comment Go to comments

Like most of the word I use Apache to serve up both my live and test websites.

The downside to having a box for development though is the constant config of apache to host these sites, most of which require absolute links (e.g. ‘/css/style.css’) to function.

The Apache snippet below sets up dynamic sub-domains which can be changed without reloading Apache every time you add, remove or update anything something. Simply drop your sites inside /var/www whenever you want a new subdomain. Alternatively you can symlink if they are hosted elsewhere on the box.

Its pretty easy to install, simply paste the below in your /etc/apache2/apache.conf file…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Easy virtual host config
# See http://hashbang.net/2009/03/easy-apache-virtualhosteasy-apache-virtualhost/
<VirtualHost *>
DocumentRoot /var/www/
ServerAdmin admin@localhost
Options +FollowSymLinks -Indexes
LogLevel debug
ServerAlias localhost
ServerName localhost
RewriteEngine  on
RewriteLogLevel 3
RewriteCond    %{HTTP_HOST}  ^localhost
RewriteRule    ^(.*)$        /www/$1 [L]
RewriteCond    %{HTTP_HOST}  ^www.*
RewriteRule    ^(.*)$        /www/$1 [L]
RewriteCond    %{HTTP_HOST}  ^(.*)\.localhost
RewriteRule    ^(.*)$        /%1/$1 [L]
</VirtualHost>

Now add your servers to the /etc/hosts file:

127.0.0.1      server.localhost

Now any directory you place in the /var/www directory automatically becomes a subdomain. You can now visit http:///server.localhost as a fully fledged webhost.

If you want to use another name than the rather boring ‘localhost’ simply replace the text in both text pastes above.

If only there were a way of removing that /etc/hosts hack it would mean zero config from then on. If anyone has any ideas do let me know. The addition to the hosts file seems to need applying if you are working from the same box the Apache server resides on. If you arn’t and the box is a local dedicated server its not needed at all and domains can be added and removed as necessary.

Categories: HowTo's Tags: , ,
  1. scott
    January 15th, 2011 at 05:08 | #1

    cool idea

  1. No trackbacks yet.
*