views:

425

answers:

3

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.

A: 

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
This will redirect all traffic to domain1.com, I need the traffic to remain on their respective sites, whilst removing the 'www'.
Nick Sergeant
All right, updated — the pattern's the same, of course.
bobince
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
Yes, it will retain the trailing URL fine.
bobince
A: 

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
This simply sets up aliases for each domain, it does not redirect traffic from www.domain1.com to domain1.com.
Nick Sergeant
+1  A: 

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
Perfect, thanks!
Nick Sergeant