How to redirect non www to www domain

August 11, 2014 2.3k views

I have successfully followed the tutorial: How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTS.

I can access mysite.co.uk and also www.mysite.co.uk

However, I would like to show www.mysite.co.uk when I type in mysite.co.uk

I have tried a 301 direct in the virtual host file but that didn't work, neither did creating a an .htaccess file and using the following code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [nocase]
RewriteRule ^(.*) http://www.example.com/$1 [last,redirect=301]

Edit: I have already amended the apache2.conf to AllowOverride All and created an .htaccess file in the root of the site directory.

Thank you for any assistance.

1 Answer

That way I would do it is creating a new VirtualHost for mysite.co.uk and having it redirect to www.mysite.co.uk:

<VirtualHost *:80>
ServerName mysite.co.uk

Redirect 301 / http://www.mysite.co.uk
</VirtualHost>

Make sure you remove any instances of mysite.co.uk in your current VirtualHost (ServerName and ServerAlias) and restart Apache:

sudo service apache2 restart
Have another answer? Share your knowledge.