Tip: Ubuntu 20.04 is an older release. Newer Ubuntu versions use the same steps.
What is a virtual host?
Apache is a web server program. A virtual host is a set of rules for one website. It lets one server serve many sites, like one apartment block with many flats. Each flat has its own name on the door.
Steps
- Log in to your server over SSH.
- Install Apache:
sudo apt update sudo apt install apache2 -y - Create a folder for your site's files:
sudo mkdir -p /var/www/example.com/public_html - Give your user ownership of it:
sudo chown -R $USER:$USER /var/www/example.com/public_html sudo chmod -R 755 /var/www/example.com - Create a test page:
Type a short line such asnano /var/www/example.com/public_html/index.html<h1>Welcome to example.com</h1>. Press Ctrl+O, then Enter to save, and Ctrl+X to leave. - Create the virtual host file:
sudo nano /etc/apache2/sites-available/example.com.conf - Put this inside it:
Change<VirtualHost *:80> ServerAdmin webmaster@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 </VirtualHost>example.comto your own domain. - Turn on your new site:
sudo a2ensite example.com.conf - Turn off the default Apache site, if you do not need it:
sudo a2dissite 000-default.conf - Check for mistakes:
You should see "Syntax OK".sudo apache2ctl configtest - Restart Apache:
sudo systemctl restart apache2 - If the firewall UFW is on, allow web traffic:
sudo ufw allow 'Apache Full' - Point your domain's A record to the server IP. An A record links a domain name to a number address. Then open your domain in a browser.
For a second website, repeat steps 3 to 11 with another domain name and folder.
Tip: Add free HTTPS later with Certbot. It adds a second virtual host for port 443 for you.
Warning: the command a2dissite removes a site from the active list. Check which site you are turning off, so you do not take a live site offline.
Quick recap
- A virtual host lets one server show many sites.
- Make a folder and a
.conffile for each site. - Use
a2ensiteto switch it on. - Run
apache2ctl configtest, then restart Apache. - Point the domain to your server.