How to redirect non www to www domain

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

I can access and also

However, I would like to show when I type in

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} ^ [nocase] RewriteRule ^(.*)$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.

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

I had the same problem. Then I figure it out and wrote a content regarding this issue. If you want the best and easiest way then visit you will find the answer both for non-www to www and www to non-www

That way I would do it is creating a new VirtualHost for and having it redirect to

<VirtualHost *:80>

Redirect 301 /

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

sudo service apache2 restart