Apache – How to Redirect URL Within Apache VirtualHost

apache-2.2mod-rewriteredirectvirtualhost

I have a dedicated server with Apache, on which I've set up some VirtualHosts. I've set up one to handle the www domain as well as the non-www domain.

My VH .conf file for the www:

<VirtualHost *>
  DocumentRoot /var/www/site
  ServerName www.example.com
  <Directory "/var/www/site">
    allow from all
  </Directory>
</VirtualHost>

With this .htaccess:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Is there a simple way to redirect the www to the non-www version? Currently I'm sending both versions to the same DocumentRoot and using .htaccess but I'm sure I must be able to do it in the VirtualHost file.

Best Answer

Turns out mod_rewrite rules are fine in the VirtualHosts file, apart from the RewriteBase rule. I ended up with this:

<VirtualHost *>
  ServerName www.example.com
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www.example.com
  RewriteRule ^/(.*)$ http://example.com/$1 [L,R=301]
</VirtualHost>

EDIT: on the advice of joschi in the comments, I'm now using this simplified version using the Redirect directive from mod_alias:

<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>
Related Topic