I have a usecase where I need to setup wildcard subdomains with condition so that for http://xyz.example.com type of request it should choose document root as /var/www/html/web and for http://xyz-portal.example.com it should choose document root as /var/www/html/admin. How this can be achieved?
1 Answers
Generate different virtualhosts with a default name resembling each case and then use ServerAlias for the wildcard. This is a example, adjust to your needs considering the following explanation.
Example:
<VirtualHost *:80>
ServerName www-portal.example.com
ServerAlias *-portal.example.com
DocumentRoot /var/www/html/admin
...
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
ServerAlias *.example.com
DocumentRoot /var/www/html/web
...
</VirtualHost>
Explanation:
ServerName does not take in wildcards, so you must define it with the main "default" virtualhost name matching the scheme you want to use, then you use ServerAlias with wildcards or several entries to match all those domain requests that have to land in the same virtualhost
Note the xyz-portal.example.com must be defined first. Why? Because the generic wildcard of the other virtualhost serveralias "*.example.com" would match and grab the request if defined first. Apache selects virtualhost to reply based on Host header requested and first match in the order of loaded virtualhost wins.

- 2,727
- 1
- 13
- 19