how to connect to one of multiple virtual sites (apache 2.4)

If I create one site, I can access it with http://localhost ...

But if I create multiple virtual sites, with apache, on the same computer, http://localhost won't work.

How can I access it? (on the same computer, aka localhost)?


To create a virtual site, try out the following commands; just replace "newsite" with the name of your site:

NOTE

  • Tested on Ubuntu 20.04, using Apache 2.4.41 and Firefox 95.0.
  • All commands were run from the home (~/) directory.
  • You must create your own index.html file in the home directory.
# Add the new site to the default Apache directory
sudo mkdir --parents /var/www/newsite

# Create your web page and place it in the directory:
sudo cp ~/index.html /var/www/newsite/index.html
sudo chmod 755 /var/www/newsite/index.html

# Copy and modify a virtual host configuration file
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/newsite.conf
sudo sed --in-place "s/webmaster@localhost/webmaster@newsite/g" /etc/apache2/sites-available/newsite.conf
sudo sed --in-place "s/DocumentRoot \/var\/www\/html/DocumentRoot \/var\/www\/newsite/g" /etc/apache2/sites-available/newsite.conf
sudo sed --in-place "/webmaster@newsite/ a ServerName newsite" /etc/apache2/sites-available/newsite.conf

# Enable the new virtual host file
sudo a2ensite newsite.conf

# Modify hosts file
sudo sed --in-place "\$a127\.0\.0\.1 newsite" /etc/hosts

# Restart Apache
sudo systemctl reload apache2

# Open the website
xdg-open http://newsite

Output:

enter image description here

You can also turn this into a shell script.