Say you want to host several websites from a single apache server each one has a different URL but how does apache know what content should go to which URL? The answer is you have to set up Virtual Hosts in your Apache httpd.conf file.
I have noticed that theres is some help for this on the web but it is challenging to figure out which line of the file does what. Here is a quick instruction on how to set up a virtual host in Apache.
First you have to ensure that Name Hosting is turned on. Through these lines:
# Ensure that Apache listens on port 80
This is just the listening port and if you are from some strange planet where web traffic is not on port 80 then, you wouldn’t be reading this blog. Hence, the question in moot.
# Listen for virtual host requests on all IP addresses
This NameVirtualHost entry MUST BE UNCOMMENTED. You can replace the * with an IP address if you have multiple networks and you want this rule to only apply to a certain network.
Next is the actual virtual host:
CustomLog logs/codesofa.com-access_log common
Here is what you need to know:
- The ServerName must match exactly with the URL that the user types in to their browswer, then the server will display whatever is in the directory of DocumentRoot.
- Since this is the First VirtualHost directive, it becomes the default. If any request comes in and doesn’t match any of the virtual host definitions, then the server will serve up whatever is in the directory of DocumentRoot.
- The DocumentRoot which is defined alone at the top of the httpd.conf file is now ignored and this entry becomes your new DocumentRoot.
Now if you want to get fancy you can try this:
CustomLog logs/linuxmaniac.net-access_log common
This looks a little different. Here is what it does:
- If the ServerName matches exactly “linuxmaniac.net”, The server serve up content from “/var/www/html/linuxmaniac” .
- If ServerName does not match exactly, it will check the ServerAlias. ServerAlias allows you to use wildcards so if a user requests “whatever.linuxmaniac.net” or “mgrecol.linuxmaniac.net” it will serve up the content in “/var/www/html/linuxmaniac” because of the * wildcard in front of linuxmaniac.net.
- Bottom Line: ServerName does not allow wild cards but ServerAlias does.
I hope that helps clear up Virtual Hosts in Apache.