Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does http://localhost redirect to my default virtual host once I setup virtual hosts in Apache?

Tags:

http

apache

This is probably an easy question, but I want to understand better how Apache works with virtual hosts. I am setting up virtual hosts because I work on multiple websites at once and I don't want to use subdirectories. I was pretty much using the default Apache httpd.conf file with the DocumentRoot pointing to something like "/www". I uncommented the virtual hosts include and added the following:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName site1.dev
    DocumentRoot /www/site1
</VirtualHost>

<VirtualHost *:80>
    ServerName site2.dev
    DocumentRoot /www/site2
</VirtualHost>

Now when I go to http://localhost I get the default page for site1.

I'm sure there is a reason why this makes sense, but I don't quite understand it. I would've thought that only requests that were explicitly to http://site1.test would get routed through that directive and it wouldn't just become the default. Can someone explain why it becomes the default.

like image 753
Bialecki Avatar asked Feb 09 '09 01:02

Bialecki


People also ask

How do I change the default virtual host in Apache?

The solution is: # apache2. conf # @warning this is specific to apache 2.2 NameVirtualHost *:80 Listen 80 # ... In my case, to work, I created a VirtualHost (n.e. VirtualHost per CNAME ) called aaaa.

What is the difference between localhost and virtual host?

Localhost: “Localhost refers to the local computer that a program is running on”. Webhosting: “In order to publish a website online, you need a Web host. The Web host stores all the pages of your website and makes them available to computers connected to the Internet”.


1 Answers

http://httpd.apache.org/docs/1.3/vhosts/name-based.html

(Should be true for 2.x also)

"If no matching virtual host is found, then the first listed virtual host that matches the IP address will be used.

As a consequence, the first listed virtual host is the default virtual host. The DocumentRoot from the main server will never be used when an IP address matches the NameVirtualHost directive. If you would like to have a special configuration for requests that do not match any particular virtual host, simply put that configuration in a container and list it first in the configuration file."

like image 76
Joe Avatar answered Sep 21 '22 13:09

Joe