For a webserver where a bunch of domain names are hosted, we'd like te implement a redirect where any subdomain on any domain is redirect to its www. equivalent.

sub1.domain1.com -> www.domain1.com
sub2.domain5.com -> www.domain5.com
anothersub.moredomains.com -> www.moredomains.com

I haven't been able to find a rewrite rule covering both wildcard subdomain and domain.

Any help is greatly appreciated!

  • In your example it's not clear how you want to specify a wildcard. Also, how many domains do you have? Different solutions are appropriate if it's a few dozen "rules" vs thousands. – Ask Bjørn Hansen Sep 19 '17 at 6:11
  • The wildcard should apply to the subdomain and the domain name. So any domain name with any subdomain should be redirected to its www. equivalent. This server hosts a few thousand domains, that's why I'm looking for a generic rule redirecting any subdomain for any domain. Hope this helps, thanks! – user3744173 Sep 19 '17 at 7:33
  • And presumably, you could have any TLD? Or is it always .com? And presumably, any number of subdomains eg. www.sub1.domain1.com? And domain1.com should also redirect to www.domain1.com? – MrWhite Sep 19 '17 at 7:48
  • Yes, that's 100% correct! – user3744173 Sep 19 '17 at 8:23

If the domains always have two components (x.tld) then it's pretty easy. If you have to take into account things like x.co.uk then you'll need either a bigger rule or an actual list of the domains.

Not tested, but something like this might work.

# enable mod_rewrite
RewriteEngine On
# if the host is prefixed with www, don't match.
RewriteCond %{HTTP_HOST} !^www\.    
# match the last two components of the hostname (see below for a bette regex)
RewriteCond %{HTTP_HOST} (.+?)\.(.+?)$
# rewrite to the hostname from the match above (%1 and %2) plus the current url ($1).
RewriteRule /(.*) http://www.%1.%2/$1 [L,R=301]


LogLevel alert rewrite:trace

and you can grep for 'rewrite:' in your error log for debugging information.

The (.+?) conditions might be more accurate as "anything but a dot" ([^\.]+), but I don't remember the exact syntax in whatever regex engine Apache uses, so the above version is simpler for you to have something working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.