redirect from non-www domain name to www using virtualhost not working

617 views Asked by At

I'm having issues redirecting my http://domain.co.uk to http://www.domain.co.uk . I'm pretty new to working with apache and linux so this is what i have done so far. Hopefully there is an obvious mistake that can be fixed easily.

In my attempt to get the redirect working I found a few tutorials saying that i should do it via the virtualhost file so i edited the existing virtual host file that i initially set up for the site in

/etc/apache2/sites-available/domain.co.uk

I have added a new block to the top of this file so it now looks like this:

<VirtualHost *:80>
    ServerName domain.co.uk
    Redirect permanent / http://www.domain.co.uk/
</VirtualHost>
<VirtualHost *:80>
  # Admin email, Server Name (domain name), and any aliases
  ServerAdmin [email protected]
  ServerName  www.domain.co.uk
  ServerAlias domain.co.uk

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html index.php
  DocumentRoot /home/simon/public/domain.co.uk/public/

  # Log file locations
  LogLevel warn
  ErrorLog  /home/simon/public/domain.co.uk/log/error.log
  CustomLog /home/simon/public/domain.co.uk/log/access.log combined
</VirtualHost>

After editing this file I restarted Apache and tried out the site but http://domain.co.uk is giving me "failed to open the page - cannot reach the server". http://www.domain.co.uk is still working fine.

Is this the right place for this <virtualhost> block? I have seen some mention of putting virtual host info in the httpd.conf file but I haven't been able to find this file in my installation of apache.

Any help would be great.

1

There are 1 answers

2
Tharanga Abeyseela On BEST ANSWER

try this one and restart Apache

<VirtualHost *:80>
    ServerName domain.co.uk
    ServerAlias *.domain.co.uk
    RedirectMatch permanent /(.*) http://www.domain.co.uk/$1
  </VirtualHost>