6

I have two domains for a website (we're using Apache), example.com and example.org. The website responds to a wildcard subdomain for both of these. I want, however, to have the .com as the canonical domain. By that, I mean, I want to redirect (301) everything to the .com, but maintain the subdomain. For example.

example.org => example.com
sub.example.org => sub.example.com

I don't know enough about regular expressions to work out how to set this up. Can anyone point me in the right direction?

Edd Morgan
  • 163
  • 5

1 Answers1

8

Try this:

<VirtualHost *:80>
    ServerName example.org
    ServerAlias *.example.org
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(.*\.)?example\.org$
    RewriteRule ^/(.*)$ http://%1example.com/$1 [R=301,L]
</VirtualHost>

..then have your other vhost (the one serving the content for example.com) configured with ServerName example.com and ServerAlias *.example.com.

Edit: made the matching of subdomains optional by adding the "?" quantifier

Shane Madden
  • 114,520
  • 13
  • 181
  • 251
  • Thanks a lot, this worked perfectly. Even better, I think I understand how it works, too. I hate just copying and pasting stuff without actually comprehending what it's doing. – Edd Morgan Aug 23 '12 at 13:15
  • @EddMorgan Great! Let me know if you'd like to see more explanation for the individual components of the config; this answer is kinda short on explanation by my standards, heh. – Shane Madden Aug 23 '12 at 17:02