Domain doesn't work without `www`

.htaccess, dns, subdomain, web

Solution

All you need is to add the following code to your root `.htaccess` file:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Problem

When I type in my domain name like without the `www` (like `http://example.com`), it doesn't work and gives error message. However, when I add the `www` to it (like `http://www.example.com`), it works. Isn't it supposed to work both ways (with and without the `www`)?

Original source