I'm using nearlyfreespeech.net as a web host, and I got tired of having to manage 3 sites for 3 subdomains on my website, so I was looking into how to serve all 3 from one site.
Each site is a shortname.nfshost.com domain, and can have an alias for a subdomain or domain. For example.com and sub.example.com, I would normally make two sites, examplewww and examplesub (I try to make the short names clear), and set www.example.com and example.com as aliases to examplewww, and sub.example.com as alias to examplesub, then point cname DNS record for the names to shortname.nfshost.com.
My solution was to make one site as PHP (since they charge more for PHP than for static), with the following:
<?php $site = $_SERVER['HTTP_HOST'];
if ($site == 'example.com') {
include('www.example.com.php'); # If domain is example.com, serve that page
} elseif ($site == 'sub.example.com') {
include('sub.example.com.php'); if domain is sub.example.com, serve that page instead
} elseif ($site == 'www.example.com') {
header('Location: http://example.com'); redirects www to no-www
} else {
header('Location: http://example.com'); don't let browser go to examplewww.nfshost.com
} ?>
The 2 included PHP files are bootstrap-themed, with CDN links for the CSS/images (bootstrap cdn, my own static site that I call a CDN (which has a complicated htaccess redirect and folders separated by site, so each site I manage can have their own images)), and besides the 404 error page (also bootstrap), these are the only files on the server (index, sub.example.com include, www.example.com include, 404).
I am able to have PHP code run within the included PHP files without a problem, and even have them include other files. The output looks normal (HTML, looks valid).
I was able to use one CMS platform, after a few glitches (setting the base_url) by including the CMS's index (as index2.php), and I sort-of got a thing working where I can deny directories if the site doesn't match (sub.example.com/folder I can return 404 if coming from www.example.com).
Question: are there any problems with this? I feel like I'm making it overly complicated, I don't know PHP very well, and I don't know if there's a problem with this that I can't think of.
I also think that if this solution was this easy, I would have seen it somewhere in my many Google searches, which makes me think it's not that good of a solution. Is there any reason not to make it this complicated?
I'm not worried about downtime, or anything like that. Besides my own visits, my site gets maybe 3 people visit a month, according to Google Analytics, and it's mostly contact info (but I have a few php scripts to show information, so I'd need to have php for all 3 subdomains, which gets to be a little more expensive with nearlyfreespeech).