HackThisSite.org News: Wildcard Subdomains

by: Kage, 07:12 pm Thursday December 20th, 2012

At one point in time we found it necessary to utilize wildcard subdomains, such as on our URL shortener. Doing this with Apache required an interesting approach via mod_rewrite:


ServerName www.domain.com
ServerAlias *.domain.com
DocumentRoot /www/domain.com/www
ServerAdmin admin@domain.com
RewriteEngine On
RewriteCond %{HTTP_HOST} (.*)\.domain\.com
RewriteCond /www/domain.com/SUB%1 !-d
RewriteRule ^/(.*)$ http://domain.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} (.*)\.domain\.com
RewriteRule ^/(.*)$ /www/domain.com/SUB%1/$1 [L]

Basically, this set a conditional match if the regular expression (.*)\.domain\.com matches the HTTP_HOST variable (the Host: HTTP header sent by the browser).

If, for example, you're requesting foobar.domain.com, this checks if /www/domain.com/SUBfoobar/ exists. If not, redirect to the root domain with whatever URI was included (appended using the $1 variable). If that directory does exist, complete the call using that directory instead of the DocumentRoot, and call $1.

As we've been migrating off Apache and onto Nginx, the need still remained for wildcard subdomains. So, we translated the same thing into Nginx:


server {
listen 80;
server_name ~^(.+\.)?domain\.com$;
set $endpath www;
if ($http_host ~* "^(.+)\.domain\.com$") {
set $endpath SUB$1;
if (!-e /www/domain.com/$endpath) {
rewrite ^ http://domain.com$request_uri? last;
location / {
root /www/domain.com/$endpath;

This does the exact same thing in Nginx by checking if the regular expression match hits, and setting the path to check. If the path doesn't exist, redirect to root, otherwise use that path.