Example VirtualHost Configurations

The excerpts below show some example name-based VirtualHost configurations that can be used in Apache.

For each TCP port that you want to use to serve content, you will need to define these before configuring your VirtualHosts. You will need both a Listen directive and a NameVirtualHost directive.

# This tells Apache to listen on port 80
Listen 80               

# This tells Apache to listen on port 443
Listen 443              

# This tells Apache that you will be using name-based vhosts on port 80
NameVirtualHost *:80 

Basic setup, using port 80, with custom log files

<VirtualHost *:80>
  ServerName www.foo.com
  
  # if you want this vhost to listen to extra names, uncomment the next line
  # ServerAlias foo.com www.bar.com bar.com
  
  DocumentRoot /var/www/www.foo.com/htdocs
  
  CustomLog /var/log/apache/www.foo.com-access.log combined
  ErrorLog /var/log/apache/www.foo.com-error.log
</VirtualHost>

Basic setup, on port 80, with multiple virtual hosts

<VirtualHost *:80>
  ServerName www.foo.com
  
  # if you want this vhost to listen to extra names, uncomment the next line
  # ServerAlias foo.com www.bar.com bar.com
  
  DocumentRoot /var/www/www.foo.com/htdocs

  CustomLog /var/log/apache/www.foo.com-access.log combined
  ErrorLog /var/log/apache/www.foo.com-error.log
</VirtualHost>

<VirtualHost *:80>
  ServerName mail.foo.com
     
  DocumentRoot /var/www/mail.foo.com/htdocs

  CustomLog /var/log/apache/mail.foo.com-access.log combined
  ErrorLog /var/log/apache/mail.foo.com-error.log
</VirtualHost>

Basic VirtualHost with custom log files and authentication

<VirtualHost *:80>
  ServerName www.foo.com
  DocumentRoot /var/www/www.foo.com/htdocs

  CustomLog /var/log/apache/www.foo.com-access.log combined
  ErrorLog /var/log/apache/www.foo.com-error.log

  AuthUserFile /var/www/www.foo.com/.htpasswd
  AuthType Basic
  AuthName "Authorised Users Only"
  Require valid-user
</VirtualHost>

SSL-enabled VirtualHost with custom log files

<VirtualHost _default_:443>
  # Only one virtual host allowed on this port, because name-based
  # virtual hosting doesn't work with SSL
  ServerName www.foo.com
  DocumentRoot /var/www/www.foo.com/htdocs

  CustomLog /var/log/apache/www.foo.com-access.log combined
  ErrorLog /var/log/apache/www.foo.com-error.log

  SSLEngine On

</VirtualHost>

ExampleVhosts (last edited 2009-09-20 22:13:35 by localhost)