The Virtual Host Issue

Suppose you are opening a website without www & it is showing different website content then issue is with your Virtual host entries. Recently I was configuring a virtual host for one of my website. After configuration I have noticed that without www first virtual host website is opening.

Example Scenario

For example, I have configured 2 virtual hosts on my server.

<VirtualHost *:80> DocumentRoot /www/example1 ServerName www.example.com # Other directives here </VirtualHost> <VirtualHost *:80> DocumentRoot /www/example2 ServerName www.example2.com # Other directives here </VirtualHost>

Why the Wrong Site Loads

When I open example2.com without www it is showing content of example.com not example2.com.

This happens because Apache, or other web servers, look for a matching ServerName or ServerAlias. If one isn't found for the non-www version, it often defaults to the first Virtual Host defined in the configuration files.

The Solution: ServerName & ServerAlias

Solution for this issue is to defining ServerName & ServerAlias Properly. For example:

  • ServerName: The primary domain (e.g., example2.com)
  • ServerAlias: The wildcard or alternative version (e.g., *.example2.com)

Here is the corrected configuration:

<VirtualHost *:80> DocumentRoot /www/example2 ServerName example2.com ServerAlias *.example2.com # Other directives here </VirtualHost>

By defining both, you ensure that requests for both example2.com and www.example2.com are routed to the correct document root.

Ucodice Team

The Ucodice Team is a group of passionate developers, designers, and strategists dedicated to delivering top-tier IT solutions to clients worldwide.