views:

588

answers:

2

My clients want to use 301 redirects to force the 'www' subdomain on their sites. So 'example.com/something' resolves to 'www.example.com/somthing' etc.

What I'm trying to do is simply add this to my vhost file:

<VirtualHost *:80>
  ServerAdmin webmaster@localhost     
  ServerName  example.com
  ServerAlias www.*
  DocumentRoot /data/apps/example.com/current/public
  RailsBaseURI / 

  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^example\.com
  RewriteRule ^ http://www.example.com%{REQUEST_URI} [L,R=301]
</VirtualHost>

I've also ensured that mod rewrite was enabled via:

sudo a2enmod rewrite
sudo /etc/init.d/apache2 force-reload

The outcome of my current efforts basically appears to be successful. Apache restarts and everything works as expected EXCEPT the rewrite isn't happening. So both 'www.example.com' and 'example.com' resolve. The browser doesn't get redirected to 'www.example.com' when it should. Any ideas? I've tried reloading the configuration and restarting apache several times but I can't seem to get the rewrite rules working. Am I setting them up in the wrong place by placing them here in the vhost instead of a .htaccess file?

Any advice here would be useful. I'm completely baffled.

+4  A: 

Put this below your main VirtualHost entry:

<VirtualHost *:80>
    ServerName example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>

You main VirtualHost should have a ServerName www.example.com entry and no aliases or redirects. Also, mod_rewrite is not required for this redirect.

cherouvim
Thanks! That is exactly what I was looking for!
Jim Jeffers
Cool, I'm happy to learn mod_rewrite is not needed for this redirect.
Luke Francl
A: 

I actually need the exact opposite of this. My application has wildcard subdomains on it and I need all www URLs to redirect to non www URLs.

www.example.com should go to example.com www.subdomain.example.com should go to subdomain.example.com

My current vhost config is as below

<VirtualHost *:80>

  ServerName  example.net
  ServerAlias *.example.net

  DocumentRoot /home/public_html/example.net/current/public

  RailsEnv staging

</VirtualHost>

Can anyone suggest what I need to do in order to get this to work? Tried various rewrite conditions in various locations but none took effect.

Vinay
You should post this as a question, not an answer to a question.
thenduks