Using the ServerPath
directive
We have a server with two name-based vhosts. In order to match the correct virtual host a client must send the correct Host:
header. Old HTTP/1.0 clients do not send such a header and Apache has no clue what vhost the client tried to reach (and serves the request from the primary vhost). To provide as much backward compatibility as possible we create a primary vhost which returns a single page containing links with an URL prefix to the name-based virtual hosts.
<VirtualHost 172.20.30.40> # primary vhost DocumentRoot "/www/subdomain" RewriteEngine On RewriteRule "." "/www/subdomain/index.html" # ... </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/subdomain/sub1" ServerName www.sub1.domain.tld ServerPath "/sub1/" RewriteEngine On RewriteRule "^(/sub1/.*)" "/www/subdomain$1" # ... </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/subdomain/sub2" ServerName www.sub2.domain.tld ServerPath "/sub2/" RewriteEngine On RewriteRule "^(/sub2/.*)" "/www/subdomain$1" # ... </VirtualHost>
Due to the ServerPath
directive a request to the URL http://www.sub1.domain.tld/sub1/
is always served from the sub1-vhost.
A request to the URL http://www.sub1.domain.tld/
is only served from the sub1-vhost if the client sent a correct Host:
header. If no Host:
header is sent the client gets the information page from the primary host.
Please note that there is one oddity: A request to http://www.sub2.domain.tld/sub1/
is also served from the sub1-vhost if the client sent no Host:
header.
The RewriteRule
directives are used to make sure that a client which sent a correct Host:
header can use both URL variants, i.e., with or without URL prefix.
Using Virtual_host
and mod_proxy together
The following example allows a front-end machine to proxy a virtual host through to a server running on another machine. In the example, a virtual host of the same name is configured on a machine at 192.168.111.2
. The ProxyPreserveHost On
directive is used so that the desired hostname is passed through, in case we are proxying multiple hostnames to a single machine.
<VirtualHost *:*> ProxyPreserveHost On ProxyPass "/" "http://192.168.111.2/" ProxyPassReverse "/" "http://192.168.111.2/" ServerName hostname.example.com </VirtualHost>