Apache website not working without www

This problem caused me a few headaches but I found the answer eventually and I reproduce it here to help any others with a similar problem.

I am running apache webserver on Linux with virtual hosting and had the following in my sites-enabled folder, in a file called example

<VirtualHost *>
DocumentRoot /home/www/web
ServerName www.example.com
ServerAlias example.com

My problem was that http://www.example.com was working as expected, but http://example.com was taking me to the “It works” apache default page. The ServerAlias directive was not working.

All my other virtual domains worked as expected.  https://another.com/ and https://www.another.com/ both pointed to the correct page. The headache was that I could see no difference between the configuration for example.com or another.com

I eventually found an answer.

In my sites-enabled directory, I have a 000-default. If apache cannot match a virtual host, for example accessing the server by an IP address, it will use the first site in the folder – 000-default in my case.

I discovered that the configuration file for my default site did not have a ServerName entry. After I added an entry ServerName default ,  http://example.com pointed to the right page.

To be honest, I cannot fully work out why. I can see that example.com may have found a match in the default but why did another.com not match?

Anyway, in summary, make sure all your site configuration files have a ServerName entry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.