Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically redirect www-based URLs to non-www URLs with multiple domains in same VirtualHost

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.

like image 735
Nick Sergeant Avatar asked Feb 09 '09 18:02

Nick Sergeant


1 Answers

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>
like image 81
bobince Avatar answered Oct 15 '22 00:10

bobince