Assuming you’ve properly installed Apache2, MySQL, PHP, and read some of the other blogs I’ve written, it’s time to add domains that point to the IP of the server, to the Apache2 as virtual hosts. This makes it easier to add files to load, per domain, even if you have multiple domains on the same IP on the server.
Add the directories for the sites we want to add:
sudo mkdir -p /var/www/example.com/public_html sudo mkdir -p /var/www/dev.example.com/public_html sudo mkdir -p /var/www/beta.example.com/public_html
Next, change the owner to the current user, and the group, this way you can sftp in later and upload the files, manage your site, etc:
sudo chown -R $USER:$USER /var/www/example.com/public_html sudo chown -R $USER:$USER /var/www/dev.example.com/public_html sudo chown -R $USER:$USER /var/www/beta.example.com/public_html
And setup the correct permissions for the www directory, recursively:
sudo chmod -R 755 /var/www
Some default data, making it easier to visually identify where we are. You can enter whatever data you want in there:
nano /var/www/example.com/public_html/index.php nano /var/www/dev.example.com/public_html/index.php nano /var/www/beta.example.com/public_html/index.php
Creating virtual host files is next, first I copy the default apache config, then I customize it to point the ServerName and ServerAlias to the right domain.
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf sudo nano /etc/apache2/sites-available/example.com.conf
Then I copy this for the next domain name, like beta or dev:
sudo cp /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-available/dev.example.com.conf sudo nano /etc/apache2/sites-available/dev.example.com.conf sudo cp /etc/apache2/sites-available/dev.example.com.conf /etc/apache2/sites-available/beta.example.com.conf sudo nano /etc/apache2/sites-available/beta.example.com.conf
Enable the virtual hosts we’ve created:
sudo a2ensite example.com.conf sudo a2ensite dev.example.com.conf sudo a2ensite beta.example.com.conf
Optionally, you can disable the default configuration; but I always leave it as a fallback:
sudo a2dissite 000-default.conf
Don’t forget to restart Apache2’s service:
sudo service apache2 restart
Pro tip; you can update your hosts file on your computer to point the ip to the domains, then restart the browser and surf to the domain names. They should now individually work, with the data you’ve set in the index.php file.
Here’s an example configuration file:
<VirtualHost *:80> ServerName beta.example.com ServerAlias www.beta.example.com ServerAdmin example@example.com DocumentRoot /var/www/beta.example.com/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>