How to Setup VirtualHost for Wildcard Subdomain in Apache


setup virtualhost for wildcard subdomain in apache

Sometimes, you may need to setup a wildcard subdomain for your website, to handle requests to any subdomain that is not specifically setup on your server. It also saves you the effort of setting up additional sub domains for your site. Let us take a look at how to setup virtualhost for wildcard subdomain in Apache.

 

How to Setup VirtualHost for Wildcard Subdomain in Apache

Here’s how to setup virtualhost for wildcard subdomain in Apache.

Let’s say you want to set up a wildcard subdomain *.example.com in your Apache server.

 

1. Open Apache config file

Open Apache config file in a text editor. You will find it at one of the following locations:

  • /etc/apache2/httpd.conf
  • /etc/apache2/apache2.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf

 


$ sudo vim /etc/apache2/httpd.conf

 

 

2. Add Virtual Hosts

We will use NameVirtualHost and ServerAlias directive to run both virtual hosts on same ip and port.

Add the NameVirtualHost directive.

Next, add a virtual host block. The key is to use ServerAlias to specify the wildcard subdomain. You cannot use a wildcard sub domain in ServerName

 


NameVirtualHost *:80
<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName www.example.com
  ServerAlias *.example.com
</VirtualHost>

If the above code doesn’t work for you, you can try using the VirtualDocumentRoot directive in addition to ServerAlias.

<VirtualHost *:80>
    ServerAlias *.example.com
    VirtualDocumentRoot /var/www/%1
</VirtualHost>  

If you want to setup multiple virtual hosts, with a few specific ones and a wildcard subdomain, you can do so by creating separate virtual hosts for specific subdomains before specifying the one for wildcard subdomain, as shown below

<VirtualHost *:80>
  DocumentRoot /var/www/app
  ServerName app.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName www.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName blog.example.com
  ServerAlias *.example.com
</VirtualHost>

In the above case, the wildcard subdomain will be matched only when the top 2 virtual hosts don’t.

 

Please Note: If you have setup separate virtual host files for each domain in Apache, then update the <VirtualHost> block in their respective files, with the ones shown above.

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! Now Apache will handle all unmatched subdomains on your web server.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!