Sunday, November 23, 2008

VirtualBox 2: Apache2 Virtual Hosts on Ubuntu

So now I've got my Ubuntu 8.04 JEOS set up in a VirtualBox set up and I'm looking at it from my host machine (which is enough if you're a developer: if you're a System's dude you should probably already know how to do this stuff). I explained how to do that here.

But I have about 5 sites I'm working on, and in PHP that's no problem because there's no real Application Root like in IIS. But I still feel that if you build the site in a subdirectory (like http://localhost/blah) something could be broken when you move it to the web root. So I set up subdomains using virtual hosts in Apache (like http://blah.localhost).

How to do it (the files move around in a bit in other Linux installations)
  1. In the directory /etc/apache2/sites-enabled place a file called blah using an editor. I use Nano (Pico)
    sudo nano /etc/apache2/sites-enabled/blah
  2. In this file I put in these contents. Note that I have chosen what I'm going to call the domain (blah.localhost), where I'm going to put the files and the error logs. Changing these to values you need is obviously the key step here.

            ServerAdmin webmaster@blah.localhost
            DocumentRoot "/var/blah"
            ServerName blah.localhost
            ErrorLog "/var/log/apache2/blah-error.log"
            CustomLog "/var/log/apache2/blah-custom.log" common
  3. Now we create the DocumentRoot directory
    sudo mkdir /var/blah
  4. And modify the hosts file to include blah.localhost. This is not actually necessary, I think, because we have to change this on the host (Windows in this case) anyway:
    sudo nano /etc/hosts
    And we add a line to hosts which says       blah.localhost
  5. Check that it works
    ping blah.localhost
  6. Set up a test file for Apache to display
    sudo nano var/blah/index.html
    with whatever contents you want (Hello Blah!)
  7. Restart Apache so it picks up the new Virtual Host
    sudo /etc/init.d/apache2 restart
  8. Try it out from inside the Guest box
    lynx blah.localhost
    You should see the Hello Blah page.
  9. Now we set up the Host to see the site. First edit the hosts file. On Windows, this is buried a bit, but you can use
    notepad c:\windows\system32\drivers\etc
    Add the line       blah.localhost
  10. Now open your browser and hit the site
Obviously, the idea is to use a folder that you mounted on your Host system for each site... the instructions are the same.

No comments: