title: How to dynamically redirect www-based URLs to non-www URLs with multiple domains in same VirtualHost
body: <p>I've got a VirtualHost that looks something like:</p>
  
  <pre><code>&lt;VirtualHost *:80&gt;
  
    ServerName  domain1.com
    ServerAlias www.domain1.com domain2.com www.domain2.com
  
  &lt;/VirtualHost&gt;
  </code></pre>
  
  <p>When someone visits www.domain1.com/test, they should be redirected to:</p>
  
  <pre><code>domain1.com/test
  </code></pre>
  
  <p>When someone visits www.domain2.com/test, they should be redirected to:</p>
  
  <pre><code>domain2.com/test
  </code></pre>
  
  <p>My current RewriteRules are lacking.</p>
  
  <p>Edit: Here's what I've got so far:</p>
  
  <pre><code># Rewrite www to non-www
  RewriteEngine on
  RewriteCond %{HTTP_HOST} www\.%{HTTP_HOST}$ [NC]
  RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
  </code></pre>
  
  <p>Obviously, this generates an infinite redirect loop.</p>