Skip to main content

Apache2 Virtual Host Configurations

Apache's virtual host configurations allow you to serve multiple websites on a single server, each with its own configuration. The <VirtualHost> directive is used to define the settings for each website.

Basic Syntax

<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.example.com
ServerAlias example.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Key Directives for Virtual Hosts

1. <VirtualHost>

Defines the virtual host. The *:80 indicates that this virtual host is listening on port 80 (HTTP). You can change the port as needed (e.g., *:443 for HTTPS).

  • Syntax: <VirtualHost [IP_address|*]:port>

2. DocumentRoot

Specifies the directory where the website’s files are stored.

  • Example: DocumentRoot /var/www/example

3. ServerName

Specifies the primary domain name for this virtual host.

  • Example: ServerName www.example.com

4. ServerAlias

Specifies additional domain names that should be handled by this virtual host (e.g., www and non-www versions, or alternate domain names).

  • Example: ServerAlias example.com *.example.com

5. ErrorLog

Specifies the file where error logs are written for this virtual host.

  • Example: ErrorLog /var/log/apache2/example_error.log

6. CustomLog

Specifies the file for the access logs and the log format.

  • Example: CustomLog /var/log/apache2/example_access.log combined

7. <Directory>

Specifies directory-level options for the virtual host, such as permissions, directory indexing, and overrides.

  • Example:
<Directory /var/www/example>
AllowOverride All
Options Indexes FollowSymLinks
Require all granted
</Directory>

8. Listen

Specifies the IP address and port on which Apache should listen. This can be configured in the main Apache config or within a virtual host block.

  • Example: Listen 80

9. DirectoryIndex

Specifies the default file that will be served if no file is requested (e.g., index.html, index.php).

  • Example: DirectoryIndex index.php index.html

10. SSLEngine (for HTTPS)

If you’re using HTTPS, you need to enable SSL in the virtual host for secure communication.

  • Enable SSL Module
sudo a2enmod ssl
sudo systemctl restart apache2
  • Generate a Self-Signed SSL Certificate
sudo mkdir -p /etc/apache2/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/apache2/ssl/apache-selfsigned.key \
-out /etc/apache2/ssl/apache-selfsigned.crt

  • Example:
<VirtualHost *:443>
DocumentRoot /var/www/example
ServerName www.example.com
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache-selfsigned.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache-selfsigned.key
</VirtualHost>

11. RewriteEngine

Enables URL rewriting, often used for redirects and clean URLs.

  • Example:
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName www.example.com
RewriteEngine On
RewriteRule ^/old-page$ /new-page [R=301,L]
</VirtualHost>

12. ProxyPass and ProxyPassReverse

Used to configure reverse proxies.

  • Example:
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName www.example.com
ProxyPass /app http://127.0.0.1:8080/
ProxyPassReverse /app http://127.0.0.1:8080/
</VirtualHost>

13. SetEnv

Used to set environment variables for the virtual host.

  • Example: SetEnv APP_ENV production

14. php_admin_value and php_value

Used to configure PHP settings for this virtual host.

  • Example:
<VirtualHost *:80>
DocumentRoot /var/www/example
php_admin_value upload_max_filesize 10M
php_value memory_limit 128M
</VirtualHost>

15. LogFormat and CustomLog

Defines the log format for access logs.

  • Example:
LogFormat "%h %l %u %t "%r" %>s %b" common
CustomLog /var/log/apache2/example_access.log common

16. AllowOverride

Specifies whether .htaccess files can override configuration settings for a directory.

  • Example: AllowOverride All

17. Require

Defines access control for the virtual host or directory.

  • Example: Require all granted (to allow all access)

18. Timeout

Sets the maximum time (in seconds) Apache will wait for certain operations.

  • Example: Timeout 300

19. KeepAlive

Determines whether persistent connections are allowed.

  • Example: KeepAlive On

Example Configurations

1. Basic HTTP Virtual Host

<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName www.example.com
ServerAlias example.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/example>
AllowOverride All
Options Indexes FollowSymLinks
Require all granted
</Directory>
</VirtualHost>

2. SSL Virtual Host (HTTPS)

<VirtualHost *:443>
DocumentRoot /var/www/example
ServerName www.example.com
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example_com.crt
SSLCertificateKeyFile /etc/ssl/private/example_com.key
SSLCertificateChainFile /etc/ssl/certs/example_com_chain.crt
ErrorLog ${APACHE_LOG_DIR}/ssl_error.log
CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
</VirtualHost>

3. Redirect Non-WWW to WWW (or vice versa)

<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
ServerName www.example.com
DocumentRoot /var/www/example
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example_com.crt
SSLCertificateKeyFile /etc/ssl/private/example_com.key
ErrorLog ${APACHE_LOG_DIR}/ssl_error.log
CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
</VirtualHost>

4. Proxy Pass Example (for reverse proxy)

<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/example
ProxyPass /api http://127.0.0.1:5000/
ProxyPassReverse /api http://127.0.0.1:5000/
</VirtualHost>

5. Prevent Host Header Injection Attacks

Set up a default virtual host to handle unexpected Host headers. This ensures no sensitive application is served for unknown hosts.

Example:

<VirtualHost *:80>
ServerName default
<Location />
Require all denied
</Location>
</VirtualHost>

<VirtualHost *:443>
ServerName default
<Location />
Require all denied
</Location>
</VirtualHost>

Including Virtual Hosts

To include multiple virtual host configurations in Apache, you can use the Include directive in the main Apache configuration file (httpd.conf or apache2.conf).

Example:

Include sites-enabled/*.conf

This allows you to separate each virtual host configuration into its own file under the sites-available or sites-enabled directory, a convention commonly used in Debian/Ubuntu systems.

Enabling a Site (Debian/Ubuntu)

After creating a configuration file for a site in /etc/apache2/sites-available/, enable it with:

sudo a2ensite example.com.conf

To disable a site, use:

sudo a2dissite example.com.conf

Then reload Apache:

sudo systemctl reload apache2

Conclusion

This guide should give you a comprehensive understanding of Apache2 virtual host configurations and how to set up and manage multiple websites on a single Apache server.

Apache .htaccess Rules and Examples

Overview

The .htaccess file is used to configure settings for Apache web servers at the directory level. Below are common examples and explanations of .htaccess rules.


1. Redirects

Redirect all HTTP traffic to HTTPS:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Redirect to a specific domain:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

2. Directory Index

Set a custom directory index:

DirectoryIndex custom_index.html

3. Access Control

Block access by IP address:

Order Deny,Allow
Deny from 192.168.1.100

Allow access only from a specific IP address:

Order Deny,Allow
Deny from all
Allow from 192.168.1.101

4. Password Protection

Protect a directory with a password:

  1. Create a .htpasswd file:
    htpasswd -c /path/to/.htpasswd username
  2. Add the following to .htaccess:
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /path/to/.htpasswd
    Require valid-user

5. Custom Error Pages

Set up custom error pages:

ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

6. Cache Control

Enable browser caching:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
</IfModule>

7. Gzip Compression

Enable Gzip compression:

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css text/javascript
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xml
</IfModule>

8. Prevent Hotlinking

Deny hotlinking of images:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]

9. Deny Directory Listing

Prevent users from seeing a list of files in a directory:

Options -Indexes

10. CORS (Cross-Origin Resource Sharing)

Allow cross-origin requests:

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

Notes

  • Ensure the .htaccess file is placed in the appropriate directory.
  • Some rules may require enabling specific Apache modules (e.g., mod_rewrite, mod_headers).