Example VirtualHost Configurations

The excerpts below show some example name-based VirtualHost configurations that can be used in Apache. For more detailed instructions, please see the official documentation.

For each TCP port that you want to use to serve content, you will need to define a Listen directive before configuring your VirtualHosts. When using Apache version 2.2.x or lower, each port will also need a NameVirtualHost directive.

# This tells Apache to listen on port 80
Listen 80               

# This tells Apache to listen on port 443 (Only required when using SSL)
Listen 443              

# This tells Apache that you will be using name-based vhosts on port 80
# Note: Only required when using Apache version 2.2.x or lower
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

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

SSL-enabled VirtualHost with custom log files

<VirtualHost *:443>
  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

  # Example SSL configuration
  SSLEngine on
  SSLProtocol all -SSLv2
  SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
  SSLCertificateFile "/var/www/www.foo.com/ssl/server.crt"
  SSLCertificateKeyFile "/var/www/www.foo.com/ssl/server.key"
</VirtualHost>

Warning: If you want to run multiple SSL vhosts on a single IP, see this article.