1

I'm trying to setup my site to use www only, and non-www should be permanently redirected to www. This answer suggested using two virtual hosts, however it causes me to go into a redirect loop.

Here's the configuration for the site:

<VirtualHost *:80>
  ServerName  www.mydomain.com

  DirectoryIndex index.html index.php
  DocumentRoot /home/me/sites/mydomain.com/htdocs

  # Log file locations
  LogLevel warn
  ErrorLog  /home/me/sites/mydomain.com/logs/error.log
  CustomLog /home/me/sites/mydomain.com/logs/access.log combined
</VirtualHost>

<VirtualHost *:80>
  ServerName mydomain.com
  Redirect permanent / http://www.mydomain.com/
</VirtualHost>

When I visit the non-www version of the site it successfully redirects to the www version, however Chrome then tells me that there was a redirect loop.

At first I thought it could be .htaccess in my document root however after removing that file it still happens. It's just a simple Wordpress site.

Can anyone see something wrong with the config that would cause this to happen? If not, how can I narrow down the cause?

Community
  • 1
  • 1
John Dorean
  • 3,744
  • 9
  • 51
  • 82

1 Answers1

1

You don't need a separate VirtualHost entry for non-www and use ServerAlias instead. Also to redirect to www just use a rule like this:

<VirtualHost *:80>
  ServerName  www.mydomain.com
  ServerAlias mydomain.com 
  DirectoryIndex index.html index.php
  DocumentRoot /home/me/sites/mydomain.com/htdocs

  # Log file locations
  LogLevel warn
  ErrorLog  /home/me/sites/mydomain.com/logs/error.log
  CustomLog /home/me/sites/mydomain.com/logs/access.log combined

  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

</VirtualHost>
anubhava
  • 761,203
  • 64
  • 569
  • 643