How to Install Apache on Ubuntu 24.04, 22.04 or 20.04

This guide will demonstrate how to install Apache on Ubuntu 24.04, 22.04, or 20.04 LTS Linux releases utilizing the command-line terminal with the APT Package Manager.

Apache HTTP Server, a robust and highly versatile web server, stands as a cornerstone of modern web hosting. Its widespread adoption is a testament to its reliability, extensive feature set, and ability to cater to websites of all sizes. Apache’s architecture is highly modular, allowing users to extend its functionalities through a wide array of modules. Here are some key highlights:

  • Open Source: Apache is developed and maintained under an open-source license, ensuring it is freely available for use and modification.
  • Cross-Platform Support: Runs on various operating systems, including Linux, Windows, and MacOS.
  • Modular Design: Offers flexibility through loadable modules to extend functionality.
  • .htaccess Support: Allows for directory-level configuration without altering server settings.
  • Virtual Hosting: Enables one Apache server to host multiple websites.
  • Security Features: Comes with robust security modules like mod_security and mod_ssl to encrypt communications.
  • Customizable Configuration: Apache’s configuration system is highly adaptable, catering to complex hosting needs.
  • Efficient Performance: Capable of handling a high volume of requests with various mechanisms to optimize performance and manage server load.

With these capabilities, Apache HTTP Server facilitates the creation and hosting of a wide range of web applications and ensures scalability, security, and efficiency. Let’s proceed to install Apache.

Install Apache on Ubuntu via APT

Update Ubuntu Before Apache Installation

Before you begin the installation process, you must update your Ubuntu operating system to ensure all existing packages are up to date. This helps you maintain a stable and secure environment.

To update your system, open the terminal and execute the following command:

sudo apt update && sudo apt upgrade

Install Apache on Ubuntu APT Command

There are two installation methods to choose from when installing Apache on Ubuntu: using the default Ubuntu repository or Ondrej Sury’s PPA.

Option 1: Install Apache with Ubuntu Default Repository

The first option to install Apache is to use the default Ubuntu repository. This method is practical for most users, providing a stable and secure version of Apache. To install Apache using the default repository, open your terminal and execute the following command:

sudo apt install apache2

After the installation is complete, verify its success by checking Apache’s build version:

apache2 --version

Option 2: Install Apache via PPA

Apache is available within Ubuntu’s software repositories by default, making it easy to install. However, like most repositories on Ubuntu LTS versions, it can often lag behind in terms of the latest features and improvements, although security risks are usually addressed.

For those who want the most up-to-date version of Apache 2 with additional widely-used modules, it is recommended to install Ondřej Surý’s version of Apache 2. To do this, follow the steps below:

Add Ondřej Surý PPA for Ubuntu with the following command:

sudo add-apt-repository ppa:ondrej/apache2 -y

Update your package list to reflect the newly imported Apache repository:

sudo apt update

Install the Apache 2 package from Ondřej Surý’s repository:

sudo apt install apache2

Once installed, confirm the version by running the following command:

apache2 -v

Configure UFW Firewall for Apache on Ubuntu

After installing the Apache web server, it’s essential to configure the UFW (Uncomplicated Firewall) rules to allow outside access to the default web ports. Apache conveniently registers itself with UFW during installation, providing several profiles to enable or disable access quickly and easily.

Check UFW Installation

Before configuring the UFW firewall, ensure that UFW is installed on your system. To check if UFW is installed, run the following command:

sudo ufw status

If UFW is not installed, you can install it with the following command:

sudo apt install ufw

After installing UFW, enable it with this command:

sudo ufw enable

List Available Application Profiles

First, list the application profiles to see the available Apache profiles by running the following command:

sudo ufw app list

Example output:

Available applications:
  Apache
  Apache Full
  Apache Secure

From the output above, you have three profile options to choose from. To break it down, Apache runs on port 80 (HTTP), Apache Secure runs on port 443 (HTTPS), and Apache Full combines both. The most common choices are either Apache Full or Apache Secure.

Configure UFW Firewall Rules for Apache

For this tutorial, since we have not set up SSL, we will enable the Apache profile with the following command:

sudo ufw allow 'Apache'

Example output:

Rule added
Rule added (v6)

As shown above, the rules have been added for IPv4 and IPv6. Later, you can disable this profile and enable secure only or disable the Apache rule and use the Apache Full rule instead.

Whitelist IP Addresses and Ranges

You can also whitelist specific IP addresses, IP ranges, or local IP addresses to grant access to your Apache web server. To allow access from a single IP address, use the following command:

sudo ufw allow from <IP_ADDRESS>

Replace <IP_ADDRESS> with the actual IP address you want to whitelist.

To allow access from a range of IP addresses, use the following command:

sudo ufw allow from <IP_RANGE> to any port <PORT_NUMBER>

Replace <IP_RANGE> with the actual range of IP addresses (e.g., 192.168.1.0/24) and <PORT_NUMBER> with the appropriate port number (e.g., 80 for HTTP or 443 for HTTPS).

To allow access from a local IP address, use the following command:

sudo ufw allow from 192.168.1.0/24

This command will allow access from all IP addresses in the 192.168.1.0/24 subnet.

Following these steps, you will have successfully configured the UFW firewall rules for your Apache web server, ensuring a secure and controlled access environment.

Verify Apache Installation on Ubuntu

Now that you have installed and configured the UFW firewall, it’s time to test if Apache 2 is reachable and working correctly by requesting a page.

Find Your Server’s IP Address

You can access the default Apache landing page to check if the software runs correctly through your server’s IP address. If you don’t know your server’s IP address, you can find it using the following command:

hostname -I

You should receive the internal IP address of the server as an example:

###Example Only###
192.168.50.15 

You may get 2 to 3 results back. Try each one until you find the correct IP address.

If you need your public IP address (external), use the following command instead:

curl -4 icanhazip.com

If the curl package is missing, you can install it by executing the following command:

sudo apt install curl -y

Access the Apache Landing Page

Once you have your server’s IP address, open your favorite internet browser and enter the following in the address bar:

http://your_server_ip

Replace your_server_ip with the actual IP address you retrieved earlier.

Verify the Apache Default Page

You should see the following page in your internet browser:

Screenshot of the Apache2 default test page on Ubuntu after installation.
The Apache2 default landing page post-installation on Ubuntu.

This page confirms that your Apache web server is up and running. This default page indicates that Apache 2 functions correctly and is reachable through the specified IP address.

Configure Virtual Hosts for Apache on Ubuntu

Using the Apache web server, you can create virtual hosts to manage configurations for multiple domains on a single server. If you have used Nginx before, virtual hosts are the equivalent of server blocks. In the example below, we will create a domain example-domain.com, which you will replace with your domain name.

Create and Configure Directories for Apache

By default, Apache on Ubuntu has one server block enabled that is configured to serve documents from the /var/www/html directory. If you operate one website, you can modify this server block to suit your needs. However, if you are hosting multiple websites, you need to create a new directory structure for your various domains.

First, leave the /var/www/html directory intact as the default directory. Then, create a new directory for example-domain.com, as shown below:

sudo mkdir /var/www/example_domain

Next, assign ownership of the directory with the $USER environment variable:

sudo chown -R $USER:$USER /var/www/example_domain

Usually, the web root permissions should be set correctly, and you can verify them using the ls -l command:

ls -l /var/www/

Example output:

drwxr-xr-x 2 joshua joshua 4096 Apr 18 15:25 example_domain
drwxr-xr-x 2 root   root   4096 Apr 18 15:23 html

As you can see, we have the permission of drwxr-xr-x, which is the equivalent of chmod 755. If you do not have this permission set, run the following command:

sudo chmod -R 755 /var/www/example_domain

Now create a sample index.html page using your favorite text editor. In this tutorial, we will use nano:

sudo nano /var/www/example_domain/index.html

In the file, copy and paste the following code:

<html>
    <head>
        <title>Welcome to Website!</title>
    </head>
    <body>
        <h1>Success! The virtual host is working! You did not mess it up.</h1>
    </body>
</html>

Save the file (CTRL+O), then exit (CTRL+X).

Create a Virtual Host for Apache

Now that you have created a landing page and set correct ownership and permissions, you can create a virtual host file. By default, all virtual host files need to be located at /etc/apache2/sites-available/ directory.

First, use your favorite text editor to create a configuration file located at /etc/apache2/sites-available/example_domain.conf:

sudo nano /etc/apache2/sites-available/example_domain.conf

Now, copy and paste the following into the configuration block file, remembering to replace your ServerName, ServerAlias, and DocumentRoot with your own:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName example_domain
    ServerAlias www.example_domain
    DocumentRoot /var/www/example_domain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Remember to change the required server directives to your own.

Save the configuration file using (CTRL+O) and exit with (CTRL+X).

Enable Virtual Host for Apache

Now that your virtual host configuration file is ready, it’s time to enable it. With Apache, unlike Nginx, where you would create a symlink using the ln -s command, Apache uses its tools, as demonstrated below:

First, disable the existing default installed server block file 000-default.conf with the a2dissite command:

sudo a2dissite 000-default.conf

Now enable your virtual host file with the a2ensite command:

sudo a2ensite example_domain.conf

Like most web server applications, Apache has a dry run function. Before making it live, test your configuration file using the following command:

sudo apache2ctl configtest

If everything is working correctly, the example output should be:

Syntax OK

Now restart the Apache web server to make your new virtual host live with the following command:

sudo systemctl restart apache2

Apache should currently serve the landing page you created for your new domain. To test this, open your internet browser and type in your domain name http://example_domain, where you should see the following landing page you created in the index.html file:

Example of an Apache Virtual Host successfully set up on Ubuntu Linux.
Title: Apache Virtual Host on Ubuntu Linux
Demonstration of a working Apache VirtualHost on Ubuntu 22.04 or 20.04.

Secure Apache with Let’s Encrypt Free SSL Certificate

To enhance the security and privacy of your website, it is essential to run your Apache web server on HTTPS using an SSL/TLS certificate. One of the best ways to achieve this is by using Let’s Encrypt, a free, automated, and open certificate authority operated by the nonprofit Internet Security Research Group (ISRG).

Install Certbot for Apache

First, you must install the certbot package, which automates obtaining and installing SSL/TLS certificates from Let’s Encrypt. Execute the following command:

sudo apt install python3-certbot-apache -y

Create and Configure SSL Certificate for Apache

Once you have installed certbot, run the following command to create your SSL/TLS certificate and configure it with your Apache web server:

sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

This command includes options for:

  • Force HTTPS 301 redirects (--redirect)
  • Strict-Transport-Security header (--hsts)
  • OCSP Stapling (--staple-ocsp)

Adjust the email address and domain name to match your requirements.

Verify SSL Configuration with Apache

Now your website’s URL should be https://www.example.com instead of http://www.example.com. If you attempt to access the website using the old HTTP URL, it will automatically redirect to HTTPS, ensuring a secure connection.

You can verify the SSL configuration by visiting your website and checking for the padlock symbol in your browser’s address bar. This symbol indicates that the connection is secure and encrypted.

Automate Certificate Renewal

Let’s Encrypt certificates are valid for 90 days, so it is crucial to set up automated renewal. By default, Certbot includes a cron job or systemd timer to handle renewals automatically. To test the renewal process manually, run the following command:

sudo certbot renew --dry-run

This command performs a dry run of the renewal process, checking whether the renewal will work without actually renewing the certificate. If the test is successful, you can be confident that your certificate will be renewed automatically before it expires.

Apache Management on Ubuntu

Now that your Apache web server is successfully running on your server, it’s essential to understand some key management aspects. This section will discuss managing server logs and basic Apache commands for day-to-day management.

Apache Server Logs

Analyzing and searching Apache logs is essential for identifying issues, monitoring user activity, and gaining insights into the server’s performance. In this section, we’ll provide some examples of Linux commands you can use to search and analyze Apache logs.

Display the last few lines of a log file:

The tail command allows you to view the last few lines of a log file. This can be useful for monitoring recent activity or errors.

tail /var/log/apache2/access.log
tail /var/log/apache2/error.log

Monitor log file in real-time:

Use the tail -f command to monitor log files in real-time, which is useful for observing live user activity or troubleshooting issues as they occur.

tail -f /var/log/apache2/access.log
tail -f /var/log/apache2/error.log

Search for specific keywords in log files:

The grep command allows you to search for specific keywords or patterns in log files. For example, you can search for occurrences of the “404” error code in the error log:

grep "404" /var/log/apache2/error.log

Count the occurrences of a specific keyword or pattern:

You can use grep in combination with the -c flag to count the occurrences of a specific keyword or pattern in log files. For example, to count the number of “500” error codes in the error log:

grep -c "500" /var/log/apache2/error.log

Display unique IP addresses that have accessed the server:

Use the awk command to display unique IP addresses that have accessed your server by analyzing the access log:

awk '{print $1}' /var/log/apache2/access.log | sort | uniq

These are just a few examples of using Linux commands to search and analyze Apache logs.

Common Apache Commands on Ubuntu

The following are some of the most common Apache commands you will use for day-to-day management when working with the Apache web server:

Stop Apache web server:

sudo systemctl stop apache2

Start Apache web server:

sudo systemctl start apache2

Restart Apache web server:

sudo systemctl restart apache2

Reload Apache web server: (For minor changes that don’t require a complete restart)

sudo systemctl reload apache2

Disable Apache on server boot:

sudo systemctl disable apache2

Enable Apache on server boot: (Automatically enabled upon installation)

sudo systemctl enable apache2

Additional Commands for Apache on Ubuntu

This section will discuss various additional commands that can help manage Apache on Ubuntu, such as updating, upgrading, and removing Apache.

Update Apache

Keeping your Apache server up-to-date is crucial to ensure security and optimal performance. To check for updates and apply them when necessary, follow these steps:

Check for available updates:

Before updating Apache, you should check for available updates for your system:

sudo apt update

Upgrade Apache:

If an Apache update is available, you can upgrade it using the following command:

sudo apt upgrade

Note that it’s always a good idea to create backups or server images if your Apache service is running critical applications. While most updates are safe, occasional issues can arise during upgrades.

Remove Apache

If you no longer require Apache on your server, you can remove it using the following steps:

To uninstall Apache, execute the command:

sudo apt remove apache2

This command will also remove any unused dependencies that were installed alongside Apache.

Conclusion

This guide covered installing, configuring, and managing Apache on Ubuntu 24.04, 22.04 or 20.04. Following the steps outlined, you should have a fully functional and secure Apache web server that can easily host multiple websites. Remember to keep your server up-to-date and maintain proper security measures to ensure a smooth user experience.

Leave a Comment


Your Mastodon Instance
Share to...