Published on Jul 15 2014 in Java Tomcat

See how random subdomains can be processed by Tomcat's default host using wildcard in DNS and webserver.

One of our clients worked on a project where he needed to service random subdomains without a need for creating them in cPanel. If you happened to have the same or similar requirement read on for guidelines.

It is generally possible by:

The rest is left to your Java web application that will see if the request came to abc.domain.com or xyz.domain.com and can respond accordingly.

Let's use _*.wildcardtest.jvmhost.net_ as our subdomains.

Webserver frontend

Assuming we already pointed the _*.wildcardtest_ and wildcardtest subdomains to correct IP (cPanel clients can use Advanced DNS Editor) we need to add

ServerAlias *.wildcardtest.jvmhost.net wildcardtest.jvmhost.net

to webserver (frontend) config (e.g. under /etc/httpd/conf/userdata/std/2/username) to ensure requests to all subdomains will reach default Tomcat host. Our cPanel clients can create wildcard '*' subdomain and then map it fully to Tomcat in Java Control Panel - Mappings. If you do not use frontend you can skip above step.

Apache Tomcat

The Alias directve of Tomcat's server.xml does not support wildcards so we need to use the default Host localhost to process the requests to random subdomains. Alternatively we could dynamically update server.xml with new Aliases and reload Tomcat but it is more complex approach.

Here is the full JSP code (1 line) that you can put in webapps/ROOT/index.jsp:

Request came to the <b><%=request.getServerName()%></b> subdomain

Now access http://abc.wildcardtest.jvmhost.net/ and see in your browser Request came to the abc.wildcardtest.jvmhost.net subdomain. Try the same with http://zzz.wildcardtest.jvmhost.net/ and see in the browser Request came to the zzz.wildcardtest.jvmhost.net subdomain. You are done with the test :)