Ubuntu Hardy - Apache Virtual Hosts #1

Now we have Apache installed and running, we can configure it to serve multiple domains using Virtual Hosts.

Do note the layout used in these articles is explained here - feel free to use the directories of your choice.


Create the layout

In this example we'll be using two domains: domain1.com and domain2.com.

In your home directory create a 'public_html' folder:

cd ~
mkdir public_html

Now for each domain we want to host create a folder with a standard set of sub-folders:

mkdir -p public_html/domain1.com/{public,private,log,cgi-bin,backup}

and

mkdir -p public_html/domain2.com/{public,private,log,cgi-bin,backup}

That will create the folders public, private, log, cgi-bin and backup for each of our domains (domain1.com and domain2.com).

index.html

The content of the public folder is, naturally, up to you but for this example I am going to use a very simple html file so we can check the virtual hosts work.

So for each domain create an index.html file:

nano public_html/domain1.com/public/index.html

add the following to the index.html file:

<html>
  <head>
    <title>domain1.com</title>
  </head>
  <body>
    <h1>domain1.com</h1>
  </body>
</html>

Repeat the process so you have a similar file for domain2.com (simply replace all instances of 'domain1.com' with 'domain2.com).

OK. Now we have a basic structure for our two domains we can look at defining two virtual hosts.

NameVirtualHost

With virtual hosts, one thing that often catches people out is the NameVirtualHost setting.

For each port that Apache listens to, we need to define a NameVirtualHost. The issue that can catch people lies in the fact that you can only define it once per port.

In itself, that's no problem but the default vhost has already defined a generic NameVirtualHost - adding another one will cause warnings and errors.

The easiest thing to do is to remove the generic NameVirtualHost from the default vhost file and then add some specific ones to the main apache config file.

That way, if we ever delete or change the default vhost we don't have to worry about where the NameVirtualHost setting is defined and so on.

OK. Let's move into the apache directory and then open the default vhost:

cd /etc/apache2/
...
sudo nano sites-available/default

Delete the 'NameVirtualHost *' line and change the next 'VirtualHost' line so the file begins like this:

<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www/

Once that is done, we can open the main apache2.conf:

sudo nano apache2.conf

Now we can add a specific NameVirtualHost setting for port 80 and a conditional one for port 443 (this conditional setting will only 'work' if we have the SSL module enabled).

So, at the bottom of the apache2.conf the following:

NameVirtualHost *:80

<IfModule mod_ssl.c>
    NameVirtualHost *:443
</IfModule>

Let's reload Apache now:

sudo /etc/init.d/apache2 reload

There should be no warnings or errors.

Nice.

Custom Virtual Hosts

We've set up the basics and now we're ready to add our own virtual hosts so we can start to serve our domains.

Let's go ahead and create the vhost file for domain1:

sudo nano /etc/apache2/sites-available/domain1.com

The contents look like this:

# Place any notes or comments you have here
# It will make any customisation easier to understand in the weeks to come

# domain: domain1.com
# public: /home/demo/public_html/domain1.com/

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@domain1.com
  ServerName  domain1.com
  ServerAlias www.domain1.com


  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/demo/public_html/domain1.com/public


  # Custom log file locations
  LogLevel warn
  ErrorLog  /home/demo/public_html/domain1.com/log/error.log
  CustomLog /home/demo/public_html/domain1.com/log/access.log combined

</VirtualHost>

a2ensite

Now we have the site available, we need to enable it:

sudo a2ensite domain1.com

The output of the command is:

Site domain1.com installed; run /etc/init.d/apache2 reload to enable.

Seems like good advice:

sudo /etc/init.d/apache2 reload

Navigate

Now navigate to your site:

http://domain1.com

Tada! You now have the contents of public/index.html being shown:

Domain1 Home Page

ServerAlias

Note that in the vhost file, we set a ServerAlias. Providing you have the DNS set up correctly you can also use that address:

http://www.domain1.com

We'll talk about forcing one address or the other in a later article about rewrite rules.

Repeat as necessary

To create and enable domain2.com simply go through the process again:

sudo nano /etc/apache2/sites-available/domain2.com
...
# Enter the details for domain2.com as per the example shown above

Then enable the site and restart Apache:

sudo a2ensite domain2.com
...
sudo /etc/init.d/apache2 reload

Finally navigate to your second domain:

http://domain2.com
or
http://www.domain2.com

All being well, you will see the 'domain2.com' index file.

Log Files

As defined in the vhosts file, each domain has its own log files. Let's take a quick look:

ls /home/demo/public_html/domain1.com/log/

The output is exactly as expected:

access.log  error.log

This makes for much easier analysis as each set of logs is self contained.

Default

Remember that although we changed the default virtual host, we did leave it in place.

Now, if someone enters the IP address of the Slice they are served the contents of that default vhosts file (providing, of course, you have not set up a separate vhost for the IP address).

Why are they served from that vhost file?

Apache searches the enabled vhosts in alphabetical order and if it can't find one for the requested IP address or domain name, it serves the first one (alphabetically).

If we had disabled or deleted the default vhost, then the contents of domain1.com would be displayed (being before domain2.com alphabetically).

This is something to keep in mind when planning your websites. Do you want a particular domain to be the default? Do you want the IP address to have completely different content?

Summary

We've gone into some detail here but, overall, setting up a virtual host is relatively easy. Of course, there are many settings and configurations to take into account but you should have your site up and running in no time.

The next virtual host article will look in more detail at some of the settings that are available and what they mean.

PickledOnion.

Article Comments:

Swaroop commented Wed May 21 18:25:21 UTC 2008:

Hey PickledOnion,

Thanks for another great precise article.

Small question though, is it better to use httpd.conf for custom configuration (which is empty in Hardy/Gutsy by default) as opposed to apache2.conf ?

Thanks, Swaroop

Nate commented Thu May 22 17:07:27 UTC 2008:

I'm getting the following error after changing the NameVirtualHost file in "sites-available/default".

Here is what I get: sudo /etc/init.d/apache2 reload apache2: Syntax error on line 298 of /etc/apache2/apache2.conf: Syntax error on line 42 of /etc/apache2/sites-enabled/000-default: Expected </virtualhost> but saw </virtualhost> ...fail!

Changing the end tag isn't recognized and throws another error. Any help?

Nate commented Thu May 22 18:13:51 UTC 2008:

I figured it out. Make sure there is a space between "NameVirtualHost" and "*:80". Correct: NameVirtualHost *:80 Wrong: NameVirtualHost*:80

Ralph commented Tue May 27 22:31:13 UTC 2008:

After adding NameVirtualHost *:80

<ifmodule> NameVirtualHost *:443 </ifmodule>

to apache2.conf and sudo /etc/init.d/apache2 reload I'm getting [warn] NameVirtualHost *:443 has no VirtualHosts Any hints?

Tony Mann commented Tue Jun 03 18:23:02 UTC 2008:

For Apache 2.2.8, the default file contains the following:

NameVirtualHost *

<VirtualHost *>

If I use the "*:80" syntax per this article, I get errors about missing hosts.

Fritz commented Mon Jun 23 21:44:36 UTC 2008:

I did all the steps, yet when i reload apache2, i get a page that used to exist to "failed to connect" when i load my website

Any ideas?

Xianhang Zhang commented Wed Jun 25 02:20:50 UTC 2008:

I am getting the same error as Fritz

Xianhang Zhang commented Wed Jun 25 21:42:56 UTC 2008:

Figured it out. Apache reload dies silently if there is a syntax error in one of the included files.

try sudo /etc/init.d/apache2 start to see if your apache server is up and running or not.

Peter Ripley commented Thu Jul 10 17:08:04 UTC 2008:

In the instructions above the following line:

"So, at the bottom of the apache2.conf the following:"

Is missing a verb. First I thought the missing verb might be "find", but since it's not there to find, I am thinking the verb should be "add".

If so, the text should read:

"So, at the bottom of the apache2.conf add the following:"

duard commented Tue Jul 15 06:19:55 UTC 2008:

:-( ,

sudo a2ensite domain1.com Site domain1.com installed; run /etc/init.d/apache2 reload to enable. aquino@adagas:/etc/apache2$ sudo /etc/init.d/apache2 reload

  • Reloading web server config apache2 [ OK ]

and

"failed to connect"

duard commented Tue Jul 15 06:27:56 UTC 2008:

:-D

http://localhost/ show me domain1.com

and

http://localhost/ domain1.com

I put "NameVirtualHost *" on /etc/apache2/sites-available/default and reload apache

ps. sorry my english !

Syed Muzammil Ali commented Tue Aug 12 11:10:47 UTC 2008:

After adding

NameVirtualHost *:80

<ifmodule> NameVirtualHost *:443 </ifmodule>

to apache2.conf and sudo /etc/init.d/apache2 reload I'm getting apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

I am configuring multiple domains.

Eddie commented Thu Aug 14 02:26:44 UTC 2008:

For those who are getting the default site when they type their URL (instead of your vhost), I've found the solution. The virtual hosts here are described as *:80, which is fine, but the default site config file is listening for just * (no port specified). For whatever reason, Apache matches that first. Change your default config to read: <VirtualHost *:80> restart, and it will run like a champ.

Hope that helps someone.

Max commented Sat Aug 16 18:18:08 UTC 2008:

Eddie, the instructions already suggest doing that (search 'Delete the 'NameVirtualHost *' line and change the next 'VirtualHost' line so the file begins like this:').

Anyone else getting a simple [fail] when trying to start apache2? I wish there was some other output...

Max commented Sat Aug 16 18:23:20 UTC 2008:

Oops, forgot to s/demo/home/ one spot of my vhost file. Nevermind!

freshcutsalads.com commented Mon Aug 18 22:23:18 UTC 2008:

I set my document root to /var/www/public_html/domain1.com/public and was getting a 403 error until I did:

:/var/www/public_html$ sudo chmod -R 755 *

Hopefully that will help someone with the same problem.

veera commented Fri Aug 22 12:00:44 UTC 2008:

After following all the steps for two virtual hosts, and giving http://domain1.com in the browser, I am getting the following error.

The requested URL could not be retrieved

While trying to retrieve the URL: http://www.domain1.com/

The following error was encountered:

Unable to determine IP address from host name for www.domain1.com

The dnsserver returned:

Server Failure: The name server was unable to process this query.

This means that:

The cache was not able to resolve the hostname presented in the URL. Check if the address is correct.

Your cache administrator is root.

Generated Fri, 22 Aug 2008 10:27:05 GMT by localhost.localdomain (squid/2.5.STABLE6)

homayoon taheri commented Wed Aug 27 07:50:19 UTC 2008:

I have this problem too.

rubyonrails commented Fri Sep 05 01:46:45 UTC 2008:

Address Not Found

Firefox can't find the server at www.domain1.com.

The browser could not find the host server for the provided address.

* Did you make a mistake when typing the domain? (e.g. "ww.mozilla.org" instead of "www.mozilla.org")
* Are you certain this domain address exists?  Its registration may have expired.
* Are you unable to browse other sites?  Check your network connection and DNS server settings.
* Is your computer or network protected by a firewall or proxy?  Incorrect settings can interfere with Web browsing.

rubyonrails commented Fri Sep 05 01:48:06 UTC 2008:

I tried all this for several times and I am getting same error each time. Can you suggest some solution. I am on ubuntu

Eric Ferraiuolo commented Sun Sep 14 21:49:22 UTC 2008:

I was getting [warn] messages when following the instructions and setting the following line in the default site's config file.

<VirtualHost *:80>

The message was (note: I have mod_ssl enabled): [warn] NameVirtualHost *:443 has no VirtualHosts

I was able to get this message to go away when I changed the VirtualHost line to the following: <virtualhost>

Eric Ferraiuolo commented Sun Sep 14 21:50:36 UTC 2008:

...guess I didn't do that write, what I changed the VirtualHost line to the following:

<VirtualHost *:80 *:443>

Sorry...

mike k commented Thu Sep 18 09:03:14 UTC 2008:

I am getting the page Page Load Error, same as above but for the second page. The first page works great. Does there have to be a different port specified for the second page? Maybe additional DNS settings in the slicehost manager I need to do?

Address Not Found

Firefox can't find the server at blah.

The browser could not find the host server for the provided address.

* Did you make a mistake when typing the domain? (e.g. "ww.mozilla.org" instead of "www.mozilla.org")
* Are you certain this domain address exists?  Its registration may have expired.
* Are you unable to browse other sites?  Check your network connection and DNS server settings.
* Is your computer or network protected by a firewall or proxy?  Incorrect settings can interfere with Web browsing.

Nir commented Fri Sep 19 04:05:21 UTC 2008:

This is for those of you who can't start their apache server:

An older version of this article instructed to create public_html/mydomain.com/logs

In this version of the article logs has been changed to log. If you base your new virtual host on an old version make sure it points to the correct log folder.

Sipskin commented Sun Oct 19 19:38:56 UTC 2008:

Excellent tip, Nir. I had the exact same problems to everyone above - apache kept failing to start - but once I changed the entry for the log paths inside the virtual host to the correct one, it worked fine for me.

Thanks once again.

Ramon commented Tue Oct 21 09:09:58 UTC 2008:

im getting an error after adding NameVirtualHost *:80

  • Reloading web server config apache2 [Tue Oct 21 02:08:10 2008] [error] (EAI 5)No address associated with hostname: Could not resolve host name *;80 -- ignoring!

ANY HELP PLEASE,I REALLY NEED HELP THANK YOU!!!!!!!!

PickledOnion commented Tue Oct 21 09:27:28 UTC 2008:

Ramon,

Please don't shout (use capitals), it doesn't make anyone help you any quicker.

The error is shown quite clearly - you are using a semi-colon (;) instead of a colon (:)

Part of being a good sysadmin is the details - easy mistake to make but the error is clearly shown.

PickledOnion

Ramon commented Tue Oct 21 09:41:49 UTC 2008:

sorry about the capital letters i apologyze it wasn't my intentions my english grammar is not that well,but thanks for the answer i got it donde few swconds after i posted i want it to post back again to say i got it done but the last reload i have to do im gettinf and error,please any help

peralta@peralta-desktop:~$ sudo /etc/init.d/apache2 reload

  • Reloading web server config apache2 [Tue Oct 21 02:37:09 2008] [warn] default VirtualHost overlap on port 80, the first has precedence

Ramon commented Wed Oct 22 00:48:47 UTC 2008:

i know that means i need another port but how i fix this if your manual says port 80,what should i do,any help please? i have cox internet 12mbps/8mbps and im behind a linksys router and the modem running linux ubuntu server edition 8.04lts,im not a expert but i got to the last part i just wanna get it done

TJ commented Wed Oct 22 03:51:40 UTC 2008:

I followed this guide twice and it worked great. I tried to add a third and I keep getting Safari can’t find the server. Safari can’t open the page “http://mag.mysite.com/” because it can’t find the server “mag.mysite.com”.

I ping mag.mysite.com and it resolves.

any ideas on what is wrong?

nick commented Tue Oct 28 19:45:36 UTC 2008:

I tried like 4-5 times with my slice and cannot get it to work.......I think I am missing some sort of variable.....like namevirtualhost=mydomain.com ? Any ideas help would be appreciated.

A83 commented Sun Nov 02 22:39:24 UTC 2008:

If I have multiple TLDs registered for a name/site. How do I set that up? For example I want mydomain.com, mydomain.net and mydomain.org to go to the same content on slicehost...

Thanks in advanced!

Richard commented Wed Nov 19 06:06:24 UTC 2008:

@Ramon: This is support for Slicehost, check the Ubuntu forums for help with your server at home.

Robert commented Mon Dec 15 23:46:48 UTC 2008:

Hi :) Any ideas, why my site loads with my first domain, but not with my second comaind or just the IP address? sites-available/default looks like

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@robsite.net
  ServerName  217.115.143.140

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/admin/public_html/robsite.net/current/public


  # Custom log file locations
  LogLevel warn
  ErrorLog  /home/admin/public_html/robsite.net/current/log/error.log
  CustomLog /home/admin/public_html/robsite.net/current/log/access.log combined

</VirtualHost>

That doesn't work. http://217.115.143.140/ -> connection refused.

What does work is my first domain:

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@robsite.net
  ServerName  robsite.net
  ServerAlias www.robsite.net


  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/admin/public_html/robsite.net/current/public


  # Custom log file locations
  LogLevel warn
  ErrorLog  /home/admin/public_html/robsite.net/current/log/error.log
  CustomLog /home/admin/public_html/robsite.net/current/log/access.log combined

</VirtualHost>

But again, not the second.

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@robsite.net
  ServerName  second-domain.com
  ServerAlias www.second-domain.com


  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/admin/public_html/second-domain.com

</VirtualHost>

Of course /home/admin/public_html/second-domain.com exists, all the sites are enabled and Apache is reloaded

Greetings from Germany, Rob

Robert commented Tue Dec 16 13:30:44 UTC 2008:

Erm, nevermind. I just used the wrong IP /:D

Andrew Bessa commented Tue Dec 16 18:03:14 UTC 2008:

I was trying to search for an answer to the following problem: "apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName" Where is the ServerName configured?

Any help is appreciated... thanks!

PickledOnion commented Wed Dec 17 12:05:34 UTC 2008:

Andrew,

Please see the other apache articles for the solution or enter it into the search box on the main page.

Cheers, PickledOnion

Pandian commented Tue Jan 06 10:37:39 UTC 2009:

I am installing openfire server on our company slice and I don't Know how to configure it via two ports or make a virtualhost to manage these two ports using apache2 9090 : server port (The admin console port) 5332 : client port (Spark client) Thanks in advance

Nimish commented Wed Mar 04 21:27:47 UTC 2009:

sudo nano /etc/apache2/sites-available/domain1.com creates the vhost file. What is the command needed to delete it?

Joe Ybarra commented Tue Mar 10 03:16:22 UTC 2009:

Thank you for the great articles. I am a beginner and set everything up according to the article but found that I would receive an "unable to establish a connection" error. Thanks to a forum topic at http://forum.slicehost.com/comments.php?DiscussionID=1940&page=1#Item_0 I learned that a soft reboot was neccessary for it to work for me. I am not sure if that was a common practice but hopefully this helps someone else.

Jacob Grahn commented Fri Mar 20 08:36:47 UTC 2009:

Just in case you're a little dull like me, the directories you enter in the virtual hosts have to actually exist. Apache will silently die if they don't, and you won't be able to start Apache again until you fix it.

Billy K commented Wed Mar 25 21:14:16 UTC 2009:

Hello, I followed along by the book and when I entered http://domain1.com in the browser it never served up the page, just spins and spins until I get the dreaded:

Address Not Found Firefox can't find the server at www.domain1.com.

Any clues anyone???

Anders Jørgensen commented Tue May 26 07:37:18 UTC 2009:

You don't have to add DirectoryIndex index.html unless you want to use a none-default index file like foobar.lol. If you add it, remember to add index.php to it, if you are using PHP.

aamir attaa commented Fri Aug 07 05:27:11 UTC 2009:

thumbs up, great guy you are : - )

Kumi commented Mon Aug 10 21:58:39 UTC 2009:

Pickled Onion, great article as always. I've followed seven of your articles already and have come this far! I have one question about permissions. If I do choose to create the public_html dir under /var/www, would I have to do all of that as root (or sudo) and maintain the user:group to be the same as other things under /var/www? I'm assuming when they're created under the home dir, they're all inheriting user:group from the home dir.

ize commented Tue Sep 29 03:31:37 UTC 2009:

Thanks for all the great tutorials. A minor clarification here would be helpful/reassuring for beginners like me:

"Let's go ahead and create the vhost file for domain1:

sudo nano /etc/apache2/sites-available/domain1.com

The contents look like this:

# Place any notes or comments you have here ... [etc]

I am guessing that this means I should copy/paste the content above into the new, blank file that is created by the sudo nano /etc/apache2/sites-available/domain1.com command. Is that correct?

Jason Nerida commented Tue Sep 29 17:28:52 UTC 2009:

I've deleted the NameVirtualHost line from /etc/apache2/sites-available/default; added the conditional in /etc/apache2/apache2.conf; defined two custom virtual hosts in /etc/apache2/sites-available/domain1.com and /etc/apache2/sites-available/domain2.com.

I'm able to view the first domain but the second renders as a 404 and I get this warning when reloading apache2:

[Tue Sep 29 16:41:35 2009] [warn] module wsgi_module is already loaded, skipping [Tue Sep 29 16:41:35 2009] [warn] NameVirtualHost *:80 has no VirtualHosts ...done.

Jason Nerida commented Tue Sep 29 17:51:14 UTC 2009:

I fixed the rendering problem but I still get the warning:

[Tue Sep 29 16:41:35 2009] [warn] module wsgi_module is already loaded, skipping [Tue Sep 29 16:41:35 2009] [warn] NameVirtualHost *:80 has no VirtualHosts ...done.

Tracy commented Sat Nov 21 08:56:40 UTC 2009:

Joe Ybarra you are a life saver. I was redoing all the virtual host setup and nothing was wrong with any of the setups. The apache default had worked before then stopped. Finally I saw your post, did a soft reboot and the vh is working!

I should have known by now that reboot can solve strange problems.

Ben M commented Mon Dec 21 04:23:23 UTC 2009:

@Joe Ybarra, you rock!

I followed the tutorial word for word, but in the end my domain could not be found.

I typed the command 'apache2 restart' instead of 'apache2 reload' and it worked!

3 idiots commented Sun Jan 17 20:40:25 UTC 2010:

Finally my problem is solved thanks for the tutorial man

Francisco Vargas-Mejorada commented Mon Mar 01 17:10:54 UTC 2010:

When I write de domain name i cant get my site but if i write de ip address i can get the index.html file, help.

Humza Bobat commented Tue Oct 26 20:34:57 UTC 2010:

I followed the instructions for the domain1.com , but what do i point my domain to?

Raydon commented Thu Jan 13 17:49:12 UTC 2011:

I just finished the guide and completed the setup. I can navigate the site everything displays correctly. However, when i attempt to access the page via https the browser displays a message saying that it cannot connect to the server (not a 404 message). Any ideas about what I am doing wrong?

Thanks for the great work so far.

Jered commented Thu Jan 13 22:10:38 UTC 2011:

Raydon, it sounds like either the SSL module isn't enabled for your virtual host, or apache doesn't like the way SSL is configured. You might look at this article on SSL certificates to see if that helps any. At worst you can also check the apache documentation page.

Jayendra commented Tue Nov 22 04:49:34 UTC 2011:

Hi,

I am getting the same issue.

I am using ubuntu OS and I have created different files in sites-available directory in apache directory.

when I reload the apache, I am getting the error of virtual host overlapping other virtual host.

Kindly suggest me

Thanks

Jered commented Wed Nov 23 21:31:17 UTC 2011:

It's hard to say offhand, but you might make sure the name of one of the virtual hosts isn't the same as the ServerName attribute for the apache server. When that happens it can make accessing the virtual host a little wonky.

chris wilson commented Tue Sep 18 22:39:36 UTC 2012:

Hi, I have created a video and guide for how to do this if you this helps anyone: http://www.youtube.com/watch?v=QaZBly7_0zo http://wilson18.com/how-to/linux-networking/how-to-host-multiple-sites-on-1-web-server-using-ubuntu-server-12-04/

Want to comment?


(not made public)

(optional)

(use plain text or Markdown syntax)