I think I have achieved the holy grail of generic wildcard subdomain redirection after going around in circles for a whole day battling "too many redirects" errors. It seems to work with any domain and subdomain, the only part you need to specify is a list of possible valid suffixes eg .com|.com.au|.co.uk etc. This code will take *yourdomain.suffix
for any domain and turn it into http://www.yourdomain.suffix
, but only for valid subdomains that could actually exist. You can have as many sequences of anything.anything-anything.anything-anything-anything.anything.
before yourdomain.com
as you want, it will all get turned into www. Now it seems to work perfectly, but I don't trust this sadistic language of regex one bit. I have absolutely no way of knowing if this code is valid, if it will cause server problems or fail under some important circumstances. Can anyone help bug-test or refine it?
Here it is:
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]+[a-zA-Z0-9\-]*[a-zA-Z0-9]+[\.]{1}|[a-zA-Z0-9]+[\.]{1})*([a-zA-Z0-9]+[a-zA-Z0-9\-]*[a-zA-Z0-9]+|[a-zA-Z0-9]+)\.(com|com[\.]{1}au)?$ [NC]
RewriteCond %{HTTP_HOST} !^www\.([a-zA-Z0-9]+[a-zA-Z0-9\-]*[a-zA-Z0-9]+|[a-zA-Z0-9]+)\.(com|com[\.]{1}au)?$ [NC]
RewriteRule .? http://www.%2.%3%{REQUEST_URI} [R=302,NC,L]
Note: The reason it's so long is because I'm trying to account for the possibility of dashes in the main domain or subdomain parts. So anything-anything.youdomain.com
. But I read that with domain names you're not allowed to have dashes without at least one alphanumerical character between the dash and any period. So www.anything-.yourdomain.com or www.-anything.yourdomain.com are both invalid and must be rejected. If I didn't have to consider this, the regex for the first 2 lines would be way simpler: it could just start with:
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9\-]+[\.]{1})*([a-zA-Z0-9\-]+)\.(com|com[\.]{1}au)?$