Apache Virtual Host With Dynamic subdomains
My aim is to be able to create 2 virtual hosts where one corresponds to the dev environment and another to the test environment in my local ubuntu 16.04 machine. One thing that is particular to this application is that it has to support dynamic subdomains. Some of them are fixed like login and admin subdomain, but also each user will have their own subdomain. This virtual host works fine for the dev environment:
<VirtualHost *:80>
ServerName myapp.local
ServerAlias *.myapp.local
DocumentRoot /var/www/myapp/web
<Directory /var/www/myapp/web/>
AllowOverride All
Require local
</Directory>
ErrorLog /var/www/myapp/logs/error.log
CustomLog /var/www/myapp/logs/access.log combined
</VirtualHost>
Now I want to be able to have a virtual host for the test version and access it by this url: login.test.myapp.local, admin.test.myapp.local, ... Here is the virtual host that I have that is still not working because the request always falls in the first virtual host at this time:
<VirtualHost *:80>
ServerName test.myapp.local
ServerAlias *.test.myapp.local
DocumentRoot /var/www/test.myapp/web
<Directory /var/www/test.myapp/web/>
AllowOverride All
Require local
</Directory>
ErrorLog /var/www/test.myapp/logs/error.log
CustomLog /var/www/test.myapp/logs/access.log combined
</VirtualHost>
I know that I need to tell the first virtual host to ignore urls that start with "test." and "*.test." but I do not know how to do that.
Thanks
Solution 1:
Apache interprets its configuration in the order in which it is recorded. For example we put on first place the deny directives and on the second the allow directives.
That you need is to put your virtual host configurations in a correct order. For example place the test virtual host configuration in a conf file named 001-test.myapp.local.conf
and the regular virtual host in a file named 002-myapp.local.conf
. Or if the both configurations are in one file place the test one first:
$ cat /etc/apache2/sites-available/myapp.local.conf
<VirtualHost *:80>
ServerName test.myapp.local
ServerAlias *.test.myapp.local
DocumentRoot /var/www/test.myapp/web
<Directory /var/www/test.myapp/web/>
AllowOverride All
Require local
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName myapp.local
ServerAlias *.myapp.local
DocumentRoot /var/www/myapp/web
<Directory /var/www/myapp/web/>
AllowOverride All
Require local
</Directory>
</VirtualHost>
Thus the requests that doesn't match to the first virtual host will fall into the second. Here is how it's working on Ubuntu 18.04 with Apache/2.4.29:
- additional information about the demo