How to set up virtual hosts in Apache on Ubuntu
Now that you’ve set up Apache successfully, you will probably want to set up virtual hosts for each domain hosted by the web server.
sudo mkdir -p /var/www/mydomain.com/public_html sudo mkdir -p /var/www/mydomain.com/log
This will create the domain directory if it doesn’t exist, as well as the public_html and log directories.
Now set some basic permissions for the newly created directories by issuing the following commands. As noted in the Apache install guide, you should ideally be logged in as a non-root sudo user!
sudo chown -R $USER:$USER /var/www/mydomain.com sudo chmod -R 755 /var/www
Creating a demo page for the virtual host
With the permissions set, you can now create a basic example page for mydomain.com by using your favorite text editor; mine is nano.
In this file, you can save some basic HTML to serve, such as the following:
<html> <head> <title>mydomain.com - Under Construction</title> </head> <body> <h1>Welcome to mydomain.com - something great is coming soon!</h1> </body> </html>
Creating a virtual host file for Apache
sudo nano /etc/apache2/sites-available/mydomain.com.conf
Place the following in the file, making sure to edit mydomain.com to your actual domain name.
<VirtualHost *:80> ServerAdmin [email protected] ServerName mydomain.com ServerAlias www.mydomain.com DocumentRoot /var/www/mydomain.com/public_html ErrorLog /var/www/mydomain.com/log/mydomain.com-error.log CustomLog /var/www/mydomain.com/log/mydomain.com-access.log combined </VirtualHost>
Enabling the new virtual host
sudo a2ensite mydomain.com.conf
Also, you should disable the default website by issuing the following command.
sudo a2dissite 000-default.conf
Lastly, restart the Apache web server.
sudo systemctl restart apache2
You should now be able to access your web site by navigating to mydomain.com, assuming you have updated the DNS records to point to your server’s IP address. Feel free to repeat the process for other domains.