8

I've got a VirtualHost that looks something like:

<VirtualHost *:80>

  ServerName  domain1.com
  ServerAlias www.domain1.com domain2.com www.domain2.com

</VirtualHost>

When someone visits www.domain1.com/test, they should be redirected to:

domain1.com/test

When someone visits www.domain2.com/test, they should be redirected to:

domain2.com/test

My current RewriteRules are lacking.

Edit: Here's what I've got so far:

# Rewrite www to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} www\.%{HTTP_HOST}$ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]

Obviously, this generates an infinite redirect loop.

Nick Sergeant
  • 35,843
  • 12
  • 36
  • 44

3 Answers3

10

No need for rewrites.

<VirtualHost *:80>
    ServerName domain1.com
    ServerAlias domain2.com
    ... real vhost settings ...
</VirtualHost>

<VirtualHost *:80>
    ServerName www.domain1.com
    Redirect permanent / http://domain1.com/
</VirtualHost>
<VirtualHost *:80>
    ServerName www.domain2.com
    Redirect permanent / http://domain2.com/
</VirtualHost>
bobince
  • 528,062
  • 107
  • 651
  • 834
  • This will redirect all traffic to domain1.com, I need the traffic to remain on their respective sites, whilst removing the 'www'. – Nick Sergeant Feb 09 '09 at 19:18
  • I don't believe this will retain the URL structure, will it? I would assume www.domain2.com/test1 would redirect to http://domain2.com, rather than the desired http://domain2.com/test1 – Nick Sergeant Feb 10 '09 at 03:22
  • Yes, it will retain the trailing URL fine. – bobince Feb 10 '09 at 03:28
  • 1
    This is great for SEO purposes. i.e. shifting link equity from www to non www or vice versa - which most people don't know, Google will penalize you for having duplicate content. – Jared Eitnier Oct 09 '13 at 00:29
7

Your RewriteCond is a bit wonky. I'm surprised it does anything at all, since it would seem to be trying to match the host www.domain1.com against the pattern www\.www.domain1.com. These directives worked for me:

# Redirect www to non-www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1$1 [L,R=301]
Miles
  • 31,360
  • 7
  • 64
  • 74
0

You can have multiple VirtualHosts in a configuration file, so you should change your config to this:

<VirtualHost *:80>
    ServerName domain1.com
    ServerAlias www.domain1.com
</VirtualHost>

<VirtualHost *:80>
    ServerName domain2.com
    ServerAlias www.domain2.com
</VirtualHost>

You can add another VirtualHost for each domain you want to do.

Justin Poliey
  • 16,289
  • 7
  • 37
  • 48