Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top