Virtual Hosts
I’ll never be a server administrator but sometimes I have to get my hands dirty.
When developing a website, there’s always a tricky, slightly nerve wracking, moment when you point an existing domain at the new server and hope that everything resolves correctly. Here are a few simple steps to help you set up and test virtual hosts on Apache when building a website.
How to set up and test a virtual host.
Virtual Host files are small config files which live on your apache server which tell apache which directory to return to the visitor’s web browser. You can have many virtual hosts on a server, all returning different content based on the domain name the user types into their browser.
1) This is where you can find the default virtual host:
/etc/apache2/sites-available/000-default.conf
2) Make a copy of this file to add a domain name
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf
3) Open the file with nano:
sudo nano /etc/apache2/sites-available/example.com.conf
4) Edit the files and save it.
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
5) Enable the new virtual host file:
sudo a2ensite example.com.conf
6) Restart Apache so the changes kick in:
sudo service apache2 restart
7) Open your local host file:
On your LOCAL machine (NOT your server):
sudo nano /etc/hosts
8) Add an entry for your domain name to test how the server will react upon receiving a request from a particular domain name.
Effectively, copying the way a domain name servers (DNS) works.
Add your servers IP address followed your domain name:
xxx.xxx.xxxx.xxx example.com
xxx.xxx.xxxx.xxx www.example.com
9) Save it!
10) Now you can test how your domain resolves on your server. You might have to restart your browser / clear your cache. Remember to delete this record when you’re ready to point you domain name. So you know when the DNS has updated and the domain name become available to everyone.