How to install Apache on Ubuntu 22.04
Update Ubuntu
Before we begin installing Apache, we need to make sure that Ubuntu is up to date. Open a terminal window and run the following command:
sudo apt update && sudo apt upgrade
This command will update the package list and upgrade any outdated packages.
Install Apache
Now that Ubuntu is up to date, we can install Apache. Run the following command in the terminal:
sudo apt install apache2
This will install Apache along with any necessary dependencies.
Configure Firewall
By default, Apache listens on port 80 for HTTP requests. To allow external access to the Apache server, we need to open port 80 in the firewall. Run the following command to allow incoming traffic on port 80:
sudo ufw allow 80/tcp
Test Apache
To test if Apache is working correctly, open a web browser and navigate to http://localhost/. You should see the Apache2 Ubuntu Default Page.
Configure Virtual Hosts
If you plan on hosting multiple websites on your Apache server, you can set up virtual hosts to differentiate between them. To create a virtual host, create a new configuration file in the /etc/apache2/sites-available/
directory. For example, to create a virtual host for a website called example.com
, run the following command:
sudo nano /etc/apache2/sites-available/example.com.conf
Add the following code to the file:
<VirtualHost *:80>
ServerAdmin [email protected]
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>
Save and close the file.
Next, enable the virtual host by creating a symbolic link in the /etc/apache2/sites-enabled/ directory:
sudo ln -s /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-enabled/
Finally, restart Apache to apply the changes:
sudo service apache2 restart
Test Virtual Host
To test the virtual host, add an entry to your /etc/hosts file pointing example.com to your WSL2 instance IP address:
sudo nano /etc/hosts
Add the following line:
127.0.0.1 example.com www.example.com
Save and close the file.
Next, create the document root directory for the virtual host:
sudo mkdir -p /var/www/example.com/public_html
Create an index.html
file in the document root directory:
sudo nano /var/www/example.com/public_html/index.html
Add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Example.com!</title>
</head>
<body>
<h1>Welcome to Example.com!</h1>
</body>
</html>
Save and close the file.
Finally, open a web browser and navigate to http://example.com/
. You should see the “Welcome to Example.com!” message.
That’s it! You have successfully installed Apache on Ubuntu 22.04 running in a WSL2 instance and configured a virtual host.