Redirect URL within Apache VirtualHost?

Solution 1:

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>

Solution 2:

Be very careful with 301 redirects because, by default, a browser that receives the 301 redirect will store it permanently - meaning you will give up control what that browser will see when it tries to access the domain www.example.com.

See for example this discussion http://getluky.net/2010/12/14/301-redirects-cannot-be-undon/

So either make sure it does not get cached, or use mod_proxy (I recommend the mod_proxy).

If you are fine with letting the user see the URL change on the browser address bar, use mod_rewrite:

<VirtualHost *>
 ServerName www.example.com
 RewriteEngine on
 RewriteCond %{HTTP_HOST} ^www.example.com
 RewriteRule ^/(.*)$ http://example.com/$1 [L,R=301,E=nocache:1]
## Set the response header if the "nocache" environment variable is set
## in the RewriteRule above.
 Header always set Cache-Control "no-store, no-cache, must-revalidate" env=nocache
## Set Expires too ...
 Header always set Expires "Thu, 01 Jan 1970 00:00:00 GMT" env=nocache
</VirtualHost>

If you want the "redirect" to be invisible to the user, use mod_proxy:

<VirtualHost *>
 ServerName www.example.com
 ProxyRequests Off
 <Proxy *>
 Order Deny,Allow
 Deny from all
 Allow from 203.0.113.67
 </Proxy>
 ProxyPass / http://example.com/
 ProxyPassReverse / http://example.com/
</VirtualHost>

It should be noted that mod_proxy, when badly configured, can harm your network.

Solution 3:

You can add ServerAlias example.com to the VirtualHost but the performance will differ from a redirect.

Edit

Since you want to redirect and you don't need advanced functionality, it seems like using Redirect should suffice for you. You would put the Redirect under a VirtualHost directive.

A client side solution would be to use a meta refresh tag.

  • mod_alias documentation
  • meta refresh

Solution 4:

well, you could create one virtual host for the SERVERNAME www.example.com and have it redirect to another virtual host with the servername example.com