Do I need 2 virtual hosts for both www.example.com and just example.com?

I have 2 questions - does it matter if the ServerName in Apache's conf file starts with www? Also if I have the following virtual host:

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example.com

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Should I also have the following one:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example.com

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Solution 1:

The Apache ServerName directive is used in among others the default (error) messages and headers that Apache generates. Some people prefer to have those match the hostname a site visitor used.

Then you need a VirtualHost for each and every URL hostname.

Other people prefer fewer VirtualHost blocks and use the ServerAlias directive to assign alternate names to a virtual host (when the same content can be used for all names).

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com example.net www.example.net
    ...
</VirtualHost>

Which name you use for the ServerName is as far as I know mostly a matter of preference. Some prefer the bare domain, others the www record.

And, as @HåkanLindqvist commented, you can also decide on a single URI to publish your website and redirect your other domains to that site:

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/example.com
    ...
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    Redirect "/" "http://www.example.com"
</VirtualHost>

(Where it should be noted that you should set up a TLS certificate and use and redirect to HTTPS for your sites.)