Setting Up an Ubuntu 20.04 Web Server

Among the many packages that make up the Ubuntu operating system is the Apache web server. In fact the scalability and resilience of Ubuntu makes it an ideal platform for hosting even the most heavily trafficked web sites.

In this chapter we will explain how to configure an Ubuntu system using Apache to act as a web server, including both secure (HTTPS) and insecure (HTTP) configurations.

1.1  Requirements for Configuring an Ubuntu Web Server

To set up your own web site you need a computer (or cloud server instance), an operating system, a web server, a domain name, a name server and an IP address.

In terms of an operating system, we will, of course, assume you are using Ubuntu. As previously mentioned, Ubuntu supports the Apache web server which can easily be installed once the operating system is up and running. A domain name can be registered with any domain name registration service.

If you are running Ubuntu on a cloud instance, the IP address assigned by the provider will be listed in the server overview information. If you are hosting your own server and your internet service provider (ISP) has assigned a static IP address then you will need to associate your domain with that address. This is achieved using a name server and all domain registration services will provide this service for you.

If you do not have a static IP address (i.e. your ISP provides you with a dynamic address which changes frequently) then you can use one of a number of free Dynamic DNS (DDNS or DynDNS for short) services which map your dynamic IP address to your domain name.

Once you have your domain name and your name server configured the next step is to install and configure your web server.

1.2  Installing the Apache Web Server Packages

The current release of Ubuntu typically does not install the Apache web server by default. To check whether the server is already installed, run the following command:

# apt -qq list apache

If apt generates output similar to the following, the apache server is already installed:

apache2/bionic-updates,bionic-security,now 2.4.29-1ubuntu4.13 amd64 [installed]

If the apt output does not list the package or include the [installed] status, run the following command at the command prompt to perform the Apache installation:

# apt install apache2

1.3  Configuring the Firewall

Before starting and testing the Apache web server, the firewall will need to be modified to allow the web server to communicate with the outside world. By default, the HTTP and HTTPS protocols use ports 80 and 443 respectively so, depending on which protocols are being used, either one or both of these ports will need to be opened. If your Ubuntu system is being protected by the Uncomplicated Firewall, the following command can be used to enable only insecure web traffic (HTTP):

# ufw allow Apache

To enable only secure (HTTPS) traffic:

# ufw allow 'Apache Secure'

Alternatively, enable both secure and insecure web traffic as follows:

# ufw allow 'Apache Full'

If you are using firewalld, the following commands can be used to open the HTTP and HTTPS ports. When opening the ports, be sure to specify the firewall zone that applies to the internet facing network connection:

# firewall-cmd --permanent --zone=<zone> --add-port=80/tcp
# firewall-cmd --permanent --zone=<zone> --add-port=443/tcp

After opening the necessary ports, be sure to reload the firewall settings:

# firewall-cmd --reload

On cloud hosted servers, it may also be necessary to enable the appropriate port for the server instance within the cloud console. Check the documentation for the cloud provider for steps on how to do this.

1.4  Port Forwarding

If the Ubuntu system hosting the web server sits on a network protected by a firewall (either another computer running a firewall, or a router or wireless base station containing built-in firewall protection) you will need to configure the firewall to forward port 80 and/or port 443 to your web server system. The mechanism for performing this differs between firewalls and devices so check your documentation to find out how to configure port forwarding.

1.5  Starting the Apache Web Server

Once the Apache server is installed and the firewall configured, the next step is to verify that the server is running and start it if necessary.

To check the status of the Apache service from the command-line, enter the following at the command-prompt:

# systemctl status apache2

If the above command indicates that the httpd service is not running, it can be launched from the command-line as follows:

# systemctl start apache2

If you would like the Apache httpd service to start automatically when the system boots, run the following command:

# systemctl enable apache2

1.6  Testing the Web Server

Once the installation is complete the next step is to verify the web server is up and running.

If you have access (either locally or remotely) to the desktop environment of the server, simply start up a web browser and enter http://127.0.0.1 in the address bar (127.0.0.1 is the loop-back network address which tells the system to connect to the local machine). If everything is set up correctly, the browser should load the page shown in Figure 32-1:

Figure 32-1

If the desktop environment is not available, connect either from another system on the same local network as the server, or using the external IP address assigned to the system if it is hosted remotely.

1.7  Configuring the Apache Web Server for Your Domain

The next step in setting up your web server is to configure it for your domain name. To configure the web server, begin by changing directory to /etc/apache2 which, in turn, contains a number of files and sub-directories. The main configuration file is named apache2.conf and serves as the central point for organizing the modular configuration files located in the sub-directories. For example, the apache2.conf file includes a line to import the configuration settings declared in the files located in the sites-enabled folder:

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

Similarly, the apache2.conf file imports the ports.conf file, which defines the ports on which the Apache server listens for network traffic.

To configure a web site domain on Ubuntu, begin by changing directory to /etc/apache2. In this directory you will find two sub-directories, sites-available and sites-enabled. Change directory into sites-available. In this directory you will find a default file which may be used as a template for your own site.

Copy the default file to a new file with a name which matches your domain name. For example:

# cp 000-default.conf myexample.conf

Edit your myexample.com file using your favorite editor where it will appear as follows:

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

The ServerAdmin directive defines an administrative email address for people wishing to contact the web master for your site. Change this to an appropriate email address where you can be contacted:

ServerAdmin webmaster@myexample.com

Next the ServerName directive needs to be uncommented (in other words remove the ‘#’ character prefix) and defined so that the web server knows which virtual host this configuration file refers to:

ServerName myexample.com

In the next stage we need to define where the web site files are going to be located using the DocumentRoot directive. The tradition is to use /var/www/domain-name:

DocumentRoot /var/www/myexample.com

Having completed the changes we now need to enable the site as follows:

# a2ensite myexample.conf

This command creates a symbolic link from the myexample.conf file in the sites-available directory to the sites-enabled folder.

With the site enabled, run the following command to disable the default test site:

# a2dissite 000-default.conf

Next, create the /var/www/myexample.com directory and place an index.html file in it. For example:

<html>
<title>Sample Web Page</title>
<body>
Welcome to MyExample.com
</body>
</html>

With these changes made, run the apache2ctl command to check the configuration files for errors:

# apache2ctl configtest
Syntax OK

If no errors are reported, reload the Apache web server to make sure it picks up our new settings:

# systemctl reload apache2

Finally, check that the server configuration is working by opening a browser window and navigating to the site using the domain name instead of the IP address. The web page that loads should be the one defined in the index.html file created above.

1.8  The Basics of a Secure Web Site

The web server and web site created so far in this chapter use the HTTP protocol on port 80 and, as such, is considered to be insecure. The problem is that the traffic between the web server and the client (typically a user’s web browser) is transmitted in clear text. In other words the data is unencrypted and susceptible to interception. While not a problem for general web browsing, this is a serious weakness when performing tasks such as logging into web sites or transferring sensitive information such as identity or credit card details.

These days, web sites are expected to use HTTPS which uses either Secure Socket Layer (SSL) or Transport Layer Security (TLS) to establish secure, encrypted communication between web server and client. This security is established through the use of public, private and session encryption together with certificates.

To support HTTPS, a web site must have a certificate issued by a trusted authority known as a Certificate Authority (CA). When a browser connects to a secure web site, the web server sends back a copy of the web site’s SSL certificate which also contains a copy of the site’s public key. The browser then validates the authenticity of the certificate with trusted certificate authorities.

If the certificate is found to be valid, the browser uses the public key sent by the server to encrypt a session key and passes it to the server. The server decrypts the session key using the private key and uses it to send an encrypted acknowledgment to the browser. Once this process is complete, the browser and server use the session key to encrypt all subsequent data transmissions until the session ends.

1.9  Configuring Apache for HTTPS

By default, the Apache server does not include the necessary module to implement a secure HTTPS web site. The first step, therefore, is to enable the Apache mod_ssl module on the server system as follows:

# a2enmod ssl

Restart httpd after the installation completes to load the new module into the Apache server:

# systemctl restart apache2

Check that the module has loaded into the server using the following command:

# apache2ctl -M | grep ssl_module
 ssl_module (shared)

Once the ssl module is installed, repeat the steps from the previous section of this chapter to create a configuration file for the website, this time using the sites-available/default-ssl.conf file as the template for the site configuration file.

Assuming that the module is installed, the next step is to generate an SSL certificate for the web site.

1.10 Obtaining an SSL Certificate

The certificate for a web site must be obtained from a Certificate Authority. A number of options are available at a range of prices. By far the best option, however, is to obtain a free certificate from Let’s Encrypt at the following URL:

https://letsencrypt.org/

The process of obtaining a certificate from Let’s Encrypt simply involves installing and running the Certbot tool. This tool will scan the Apache configurationfiles on the server and provides the option to generate certificates for any virtual hosts configured on the system. It will then generate the certificate and add virtual host entries to the Apache configuration specifically for the corresponding web sites.

Use the following steps to install the certbot tool on your Ubuntu system:

# apt update
# apt install software-properties-common
# add-apt-repository universe
# add-apt-repository ppa:certbot/certbot
# apt install certbot python-certbot-apache

Once certbot is installed, run it as follows:

# certbot --apache

After requesting an email address and seeking terms of service acceptance, Certbot will list the domains found in the sites-available folder and provide the option to select one or more of those sites for which a certificate is to be installed. Certbot will then perform some checks before obtaining and installing the certificate on the system:

Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: myexample.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 1
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for ebooktricity.com
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-available/myexample-le-ssl.conf
Deploying Certificate to VirtualHost /etc/apache2/sites-available/myexample-le-ssl.conf
Enabling available site: /etc/apache2/sites-available/myexample-le-ssl.conf

Certbot will also have created a new file named myexample-le-ssl.conf in the /etc/apache2/sitesavailable directory containing a secure virtual host entry for each domain name for which a certificate has been generated and enabled the site so that a link to the file is made in the /etc/ apache2/sites-enabled directory. These entries will be similar to the following:

<IfModule mod_ssl.c>
<VirtualHost *:443>
.
.
        ServerName myexample.com
        ServerAdmin webmaster@myexample.com
        DocumentRoot /var/www/myexample.com
.
.
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
.
.
SSLCertificateFile /etc/letsencrypt/live/myexample.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/myexample.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

Finally, Certbot will ask whether future HTTP web requests should be redirected by the server to HTTPS. In other words, if a user attempts to access http://www.myexample.com the web server will redirect the user to https://www.myexample.com:

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2

If you are currently testing the HTTPS configuration and would like to keep the HTTP version live until later, select the No redirect option. Otherwise, redirecting to HTTPS is generally recommended.

Once the certificate has been installed, test it in a browser at the following URL (replacing myexample.com with your own domain name):

https://www.ssllabs.com/ssltest/analyze.html?d=www.myexample.com

If the certificate configuration was successful, the SSL Labs report will provide a high rating as shown in Figure 32-2:

Figure 32-2

As a final test, open a browser window and navigate to your domain using the https:// prefix. The page should load as before and the browser should indicate that the connection between the browser and server is secure (usually indicated by a padlock icon in the address bar which can be clicked for additional information):

Figure 32-3

1.11  Summary

An Ubuntu system can be used to host web sites by installing the Apache web server. Both insecure (HTTP) and secure (HTTPS) web sites can be deployed on Ubuntu. Secure web sites use either Secure Socket Layer (SSL) or Transport Layer Security (TLS) to establish encrypted communication between the web server and client through the use of public, private and session encryption together with a certificate issued by a trusted Certificate Authority.