Serving Web Content
local graph
Chapter 14 — Serving Web Content
Section titled “Chapter 14 — Serving Web Content”The flexible nature of Ubuntu Server makes it an amazing platform on which to host your organization’s web presence. In this chapter, we’ll take a look at Apache and NGINX, which make up the leading web server software on the internet. We’ll go through installing, configuring, and extending both, as well as securing them with Transport Layer Security (TLS). In addition, we’ll also take a look at installing Nextcloud, which is a great solution for setting up your very own cloud environment for your organization to use for collaboration and sharing files. As we work through concepts related to hosting web content on Ubuntu Server, we will cover:
- Installing and configuring Apache
- Installing additional Apache modules
- Securing Apache with TLS
- Installing and configuring NGINX
- Setting up and configuring Nextcloud
To get us started, we’ll first look at configuring Apache, as well as some basic configuration.
Installing and configuring Apache
Section titled “Installing and configuring Apache”The best way to become familiar with any technology is to dive right in. We’ll begin this chapter by installing Apache. But first, what exactly is Apache? For those that aren’t already aware, Apache is a popular application that is typically run on Linux and Unix servers to serve web pages to users. It runs in the background, and serves HTML pages to those that request a URL that exists on your server.
Installing Apache is very easy; it’s simply a matter of installing the apache2 package:
sudo apt install apache2By default, Ubuntu will immediately start and enable the apache2 daemon as soon as its package is installed. You can confirm this yourself with the following command:
systemctl status apache2In fact, at this point, you already have (for all intents and purposes) a fully functional web server. If you were to open a web browser and enter the IP address of the server you just installed Apache on, you should see Apache’s sample web page:

Figure 14.1: The default sample web page provided by Apache
There you go, you have officially served web content. All you needed to do was install the apache2 package, and your server was transformed into a web server. Chapter over, time to move on.
Of course, there’s more to Apache than simply installing it and having it present a sample web page. While you could certainly replace the content in the sample web page with your own and be all set when it comes to hosting content for your users, there’s much more to understand. For instance, there are several configuration files in the /etc/apache2 directory that govern how sites are hosted, as well as which directories Apache will look in to find web pages to host. Apache also features plugins, which we will go over as well.
The directory that Apache serves web pages from is known as the document root, with /var/www/html being the default. Inside that directory, you’ll see an index.html file, which is actually the default page you see when you visit an unmodified Apache server. Essentially, this is a test page that is designed to show you that the server is working, as well as some tidbits of information regarding the default configuration.
You’re not limited to hosting just one website on a server, though. Apache supports the concept of a virtual host, which allows you to serve multiple websites from a single server. Each virtual host consists of an individual configuration file, which differentiates itself based on either name or IP address.
For example, you could have an Apache server with a single IP address that hosts two different websites, such as acmeconsulting.com and acmesales.com. These are hypothetical websites, but you get the idea. To set this up, you would create separate configuration files for acmeconsulting.com and acmesales.com and store them in your Apache configuration directory. Each configuration file would include a <VirtualHost> stanza, where you would place an identifier such as a name or IP address that differentiates one from the other. When a request comes in, Apache will serve either acmeconsulting.com or acmesales.com to the user’s browser, depending on which criteria matched when the request came in. The configuration files for each site typically end with the .conf filename extension and are stored in the /etc/apache2/sites-available directory. We’ll go over all of this in more detail shortly, so don’t worry if you don’t understand this yet.
The basic workflow for setting up a new site (virtual host) will typically be similar to the following:
- The web developer creates the website and related files
- These files are uploaded to Ubuntu Server, typically in a subdirectory of
/var/wwwor another directory the administrator has chosen - After adding the necessary files into the Document Root directory, the administrator will make sure that the
www-datauser owns all of the files within (in the case of Apache) - The server administrator creates a configuration file for the site and copies it into the
/etc/apache2/sites-availabledirectory - The administrator enables the site and reloads Apache
Enabling virtual hosts is handled a bit differently in Debian and Ubuntu than on other platforms. In fact, there are two specific commands to handle this purpose: a2ensite for enabling a site and a2dissite for disabling a site. You won’t find these commands on distributions such as CentOS, for example. Configuration files for each site are stored in the /etc/apache2/sites-available/ directory, and we would use the a2ensite command to enable each configuration. Assuming a site with the URL acmeconsulting.com is to be hosted on our Ubuntu server, we would create the /etc/apache2/sites-available/acmeconsulting.com.conf configuration file and enable the site with the following commands:
sudo a2ensite acmeconsulting.com.confsudo systemctl reload apache2I’m not using absolute paths in my examples; as long as you’ve copied the configuration file to the correct place, the a2ensite and a2dissite commands will know where to find it.
If we wanted to disable the site for some reason, we would execute the a2dissite command against the site’s configuration file:
sudo a2dissite acmeconsulting.com.confsudo systemctl reload apache2If you’re curious about how this works behind the scenes, when the a2ensite command is run against a configuration file, it basically creates a symbolic link to that file and stores it in the /etc/apache2/sites-enabled directory. When you run a2dissite to disable a site, this symbolic link is removed.
Apache, by default, will use any configuration files it finds in the /etc/apache2/sites-enabled directory. After enabling or disabling a site, you’ll need to refresh Apache’s configuration, which is where the reload option comes in. This command won’t restart Apache itself (so users who are using your existing sites won’t be disturbed) but it does give Apache a chance to reload its configuration files. If you replace reload with restart in the preceding commands, Apache will perform a full restart. You should only need to do that if you’re having an issue with Apache or enabling a new plugin, but in most cases the reload option is preferred on a production system.
The main configuration file for Apache is located at /etc/apache2/apache2.conf. Feel free to view the contents of this file; the comments contain a good overview of how Apache’s configuration is laid out. The following lines in this file are of special interest:
# Include the virtual host configurations:IncludeOptional sites-enabled/*.confAs you can see, this is how Ubuntu has configured Apache to look for enabled sites in the /etc/apache2/sites-enabled directory. Any file stored there with the .conf file extension is read by Apache. If you wish, you could actually remove those lines and Apache would then behave as it does on other platforms, and the a2ensite and a2dissite commands would no longer have any purpose. However, it’s best to keep the framework of Ubuntu’s implementation intact, as separating the configuration files makes logical sense and helps simplify the configuration. This chapter will go along with the Ubuntu way of managing configuration.
An additional virtual host is not required if you’re only hosting a single site. The contents of /var/www/html are served by the default virtual host if you make no changes to Apache’s configuration. This is where the example site that ships with Apache comes from. If you only need to host one site, you could remove the default index.html file stored in this directory and replace it with the files required by your website. If you wish to test this for yourself, you can make a backup copy of the default index.html file and create a new one with some standard HTML. You should see the default page change to feature the content you just added to the file.
The 000-default.conf file is special, in that it’s basically the configuration file that controls the default Apache sample website. If you look at the contents of the /etc/apache2/sites-available and /etc/apache2/sites-enabled directories, you’ll see the 000-default.conf configuration file stored in sites-available and symlinked in sites-enabled. This shows you that, by default, this site was included with Apache, and its configuration file was enabled as soon as Apache was installed. For all intents and purposes, the 000-default.conf configuration file is all you need if you only plan on hosting a single website on your server. The contents of this file are as follows, but I’ve stripped the comments out of the file in order to save space on this page:
<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>As you can see, this default virtual host is telling Apache to listen on port 80 for requests and to serve content from /var/www/html as soon as requests come in. The <VirtualHost> declaration at the beginning is listening to everything (the asterisk is a wildcard) on port 80, so this is basically handling all web traffic that comes into the server from port 80. The ServerAdmin clause specifies the email address that is displayed in any error messages shown if there is a problem with the site.
The DocumentRoot setting tells Apache which directory to look for in order to find files to serve as connections to this virtual host. /var/www/html is the default, but some administrators choose to customize this. This file also contains lines for where to send logging information. The access log contains information relating to HTTP requests that come in, which by default is stored in /var/log/access.log. The error log is stored at /var/log/error.log and contains information you can use whenever someone has trouble visiting your site. The ${APACHE_LOG_DIR} variable equates to /var/log by default, and this is set in the /etc/apache2/envvars file, in case for some reason you wish to change this (for example, you wish to use a custom logging directory).
If you wish to host another site on the same server by creating an additional virtual host, you can use the same framework as the original file, with some additional customizations. Virtual host files are stored in the /etc/apache2/sites-available directory, with a filename ending in .conf. Here’s an example of a hypothetical website, acmeconsulting.com. A virtual host file such as this might be saved as /etc/apache2/sites-available/acmeconsulting.com.conf:
<VirtualHost 192.168.1.104:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/acmeconsulting
ErrorLog ${APACHE_LOG_DIR}/acmeconsulting.com-error.log CustomLog ${APACHE_LOG_DIR}/acmeconsulting.com-access.log combined</VirtualHost>To save time, I’ll generally copy another virtual host file, even the default one, and change it accordingly. In this particular example, I’ve emphasized some important differences. First, with this virtual host, I’m not listening for all connections coming in on port 80; instead, I’m specifically looking for incoming traffic going to IP address 192.168.1.104 on port 80. This works because this server has two network cards, and therefore two IP addresses. With virtual hosts, I’m able to serve a different website, depending on which IP address the request is coming in on.
Next, I set DocumentRoot to /var/www/acmeconsulting. Each virtual host should have its own individual DocumentRoot to keep each site separate from the others. On my servers, I will typically disable or remove the sample virtual host (the one that has the default DocumentRoot of /var/www/html). Instead, I use /var/www as a base directory, and each virtual host gets its own directory as a subdirectory of this base.
Another change I find useful is to give each virtual host its own log files. Normally, Apache will use /var/log/apache2/error.log and /var/log/apache2/access.log to store log entries for all sites. If you only have a single site on your server, that is fine. However, when you’re serving multiple sites, I find it useful to give each site its own independent log files. That way, if you are having trouble with a particular site, you don’t have to scroll through unrelated log entries to find what you’re looking for when you’re troubleshooting. In my example, I inserted the website name in the log filenames, so this virtual host is logging errors in the /var/log/apache2/acmeconsulting.com-error.log file, and the access log is being written to /var/log/apache2/acmeconsulting.com-access.log. These log files will be created for you automatically as soon as you reload Apache.
With a server that only has a single IP address, you can still set up multiple virtual hosts. Instead of differentiating virtual hosts by IP, you can instead differentiate them by name. This is common on Virtual Private Server (VPS) installations of Ubuntu, where you’ll typically have a single IP address assigned to you by your VPS provider. For name-based virtual hosts, we would use the ServerName option in our configuration. Refer to the following example to see how this would work. With this example, I’m adding name-based virtual hosts to their own files. I called mine 000-virtual-hosts.conf and stored it in the directory. The contents are as follows:
<VirtualHost *:80> ServerName acmeconsulting.com DocumentRoot /var/www/acmeconsulting</VirtualHost>
<VirtualHost *:80> ServerName acmesales.com DocumentRoot /var/www/acmesales</VirtualHost>For each virtual host, I’m declaring a ServerName with a matching DocumentRoot. With the first example, any traffic coming into the server requesting acmeconsulting.com will be provided a DocumentRoot of /var/www/acmeconsulting. The second example looks for traffic from acmesales.com and directs it to /var/www/acmesales. You can list as many virtual hosts here as you’d like to host on your server. Providing your server has enough resources to handle traffic to each site, you can host as many as you need.
If you’re using domain names with virtual hosts, then this will only work if you set up networking such that the domain name referenced in the file resolves to the IP address of your server. Depending on your configuration, there are multiple ways to do this. If you’re using a VPS provider, such as DigitalOcean or Linode, your server will have an IP address already and you only need to edit the A Record on your DNS server to point to that IP. (The various types of DNS entries, such as an A Record, were covered in Chapter 11, Setting Up Network Services.)
If you’re running your own DNS server, you would add the A Record there. If you’re using an external DNS provider, you would log in to the dashboard for your account and add the A Record there. For testing purposes, you can edit your /etc/hosts file on your local workstation (not the server) to point to your new web server. If you’re not using a VPS provider, you would need to forward port 80 in your firewall to point to your internal web server. This is beyond the scope of this book, as there are many different models of firewalls available and it’s impossible to cover them all.
As we continue through this chapter, we’ll perform some additional configurations for Apache. At this point though, you should have an understanding of the basics of how Apache is configured in Ubuntu Server. For extra practice, feel free to create additional virtual hosts and serve different pages for them.
Installing additional Apache modules
Section titled “Installing additional Apache modules”Apache features additional modules that can be installed that will extend its functionality. These modules can provide additional features such as adding support for things like Python or PHP. Ubuntu’s implementation of Apache includes two specific commands for enabling and disabling modules, a2enmod and a2dismod, respectively. Apache modules are generally installed via packages from Ubuntu’s repositories. To see a list of modules available for Apache, run the following command:
apt search libapache2-modIn the results, you’ll see various module packages available, such as libapache2-mod-python (which adds Python support) and libapache2-mod-php8.1 (which adds PHP 8.1 support), among many others. Installing an Apache module is done the same way as any other package, with the apt install command. In the case of PHP support, we can install the required package with the following command:
sudo apt install libapache2-mod-php8.1Installing a module package alone is not enough for a module to be usable in Apache, though. Modules must be enabled in order for Apache to be able to utilize them. As mentioned earlier, we can use the a2enmod and a2dismod commands for respectively enabling or disabling a module. You can view a list of modules that are built into Apache with the following command:
apache2 -lThe modules shown in the output will be those that are built into Apache, so you won’t need to enable them. If the module your website requires is listed in the output, you’re all set.
To view a list of all modules that are installed and ready to be enabled, you can run the a2enmod command by itself with no options:

Figure 14.2: The a2enmod command showing a list of available Apache modules
The end of the output of the a2enmod command will ask you whether or not you’d like to enable any of the modules:
Which module(s) do you want to enable (wildcards ok)?If you wanted to, you could type the names of any additional modules you’d like to enable and then press Enter. Alternatively, you can press Enter without typing anything to simply return to the prompt.
If you give the a2enmod command a module name as an option, it will enable it for you. To enable PHP 8.1 (which we’ll need later), you can run the following command:
sudo a2enmod php8.1Chances are, though, if you’ve installed a package for an additional module, it was most likely enabled for you during installation. With Debian and Ubuntu, it’s very common for daemons and modules to be enabled as soon as their packages are installed, and Apache is no exception. In the case of the libapache2-mod-php8.1 package I used as an example, the module should’ve been enabled for you once the package was installed:
sudo a2enmod php8.1If a module is already enabled, you will see output similar to the following when you try to enable it with a2enmod:
Module php8.1 already enabledIf the module wasn’t already enabled, we would see the following output:
Enabling module php8.1.To activate the new configuration, you need to run:systemctl restart apache2As instructed, we’ll need to restart Apache in order for the enabling of a module to take effect. Keep in mind that restarting Apache will make any sites it may host become unavailable during the process. When it comes to disabling a module, the command syntax is fairly similar. To do so, you’ll use the a2dismod command along with the name of the module you’d like to disable:
sudo a2dismod php8.1Enabling a module that was already previously enabled will result in output similar to the following:
Module php8.1 disabled.To activate the new configuration, you need to run:
systemctl restart apache2The modules you install and enable on your Apache server will depend on the needs of your website. For example, if you’re going to need support for Python, you’ll want to install the libapache2-mod-python package. If you’re installing a third-party package, such as WordPress or Drupal, you’ll want to refer to the documentation for those packages in order to obtain a list of which modules are required for the solution to install and run properly. Once you have such a list, you’ll know which packages you’ll need to install and which modules to enable.
Securing Apache with TLS
Section titled “Securing Apache with TLS”Nowadays, it’s a great idea to ensure your organization’s website is encrypted and available over HTTPS. Encryption of web traffic has been historically achieved by utilizing Secure Sockets Layer (SSL) or, more recently, TLS, which is the successor to SSL. Both refer to a method of utilizing cryptography by installing signed certificates that protect and encrypt web traffic. The two functions are different, but the end result is the same. Going forward, it’s recommended to use TLS due to the additional security strength it offers, though it’s not uncommon to see SSL being used nowadays since it hasn’t been completely phased out.
Setting up and benefiting from TLS is not all that difficult to do, and will help protect your organization against common vulnerabilities being potentially exploited. Utilizing TLS doesn’t protect you from all exploits being used in the wild, but it does offer a layer of protection you’ll want to benefit from. Not only that, but your customers pretty much expect you to secure their communications nowadays. In this section, we’ll look at how to use TLS with our Apache installation. We’ll work through enabling it, generating certificates, and configuring Apache to use those certificates with both a single-site configuration and with virtual hosts.
By default, Ubuntu’s Apache configuration listens for traffic on port 80, but not port 443 (HTTPS). You can check this yourself by running the following command:
sudo ss -tulpn | grep apacheThe results will look similar to the following and will show the ports that Apache is listening on, which is only port 80 by default:
tcp LISTEN 0 511 *:80 *:* users:(("apache2",pid=11521,fd=4),("apache2",pid=11520,fd=4),("apache2",pid=11519,fd=4),("apache2",pid=11518,fd=4),("apache2",pid=11517,fd=4),("apache2",pid=11513,fd=4))If the server were listening on port 443 as well, we would’ve seen the following within the output:
tcp LISTEN 0 511 *:443 *:*To enable support for HTTPS traffic, we need to first enable the ssl module:
sudo a2enmod sslNext, we need to restart Apache:
sudo systemctl restart apache2In addition to the sample website we discussed earlier, Ubuntu’s default Apache implementation also includes another site configuration file, /etc/apache2/sites-available/default-ssl.conf. Unlike the sample site, this one is not enabled by default. This configuration file is similar to the sample site configuration, but it’s listening for connections on port 443 and contains additional configuration items related to TLS. Here’s the content of that file, with the comments stripped out in order to save space on this page:
<IfModule mod_ssl.c> <VirtualHost _default_:443> ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert- snakeoil.pem SSLCertificateKeyFile /etc/ssl/private/ssl-cert- snakeoil.key
<FilesMatch ".(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory>
</VirtualHost></IfModule>We already went over the ServerAdmin, DocumentRoot, ErrorLog, and CustomLog options earlier in this chapter, but there are additional options in this file that we haven’t seen yet. On the first line, we can see that this virtual host is listening on port 443. We also see _default_ listed here instead of an IP address. The _default_ option only applies to unspecified traffic, which in this case means any traffic coming into port 443 that hasn’t been identified in any other virtual host. In addition, the SSLEngine on option enables TLS traffic. Right after that, we have options for our TLS certificate file and key file, which we’ll get to a bit later.
We also have a <Directory> clause, which allows us to apply specific options to a directory. In this case, the /usr/lib/cgi-bin directory is having the SSLOptions +StdEnvVars settings applied, which enables default environment variables for use with TLS. This option is also applied to files that have an extension of .cgi, .shtml, .phtml, or .php through the <FilesMatch> option. The BrowserMatch option allows you to set options for specific browsers, though it’s out of scope for this chapter. For now, just keep in mind that if you want to apply settings to specific browsers, you can.
By default, the default-ssl.conf file is not enabled. In order to benefit from its configuration options, we’ll need to enable it, which we can do with the a2ensite command as we would with any other virtual host:
sudo a2ensite default-ssl.confEven though we just enabled TLS, our site isn’t secure just yet. We’ll need TLS certificates installed in order to secure our web server. We can do this in one of two ways, with self-signed certificates or certificates signed by a certificate authority. Both are implemented in very similar ways, and I’ll discuss both methods. For the purposes of testing, self-signed certificates are fine. In production, self-signed certificates would technically work, but most browsers won’t trust them by default and will give you an error when you go to their page. Therefore, it’s a good idea to refrain from using self-signed certificates on a production system. Users of a site with self-signed certificates would need to bypass an error page before continuing to the site, and seeing this error may cause them to avoid your site altogether. You can install the certificates into each user’s web browser, but that can be a headache. In production, it’s best to use certificates signed by a vendor.
Another method of setting up a certificate on your server is Let’s Encrypt, a popular (and free) service for encrypting web traffic. Consider checking out the instructions at the Let’s Encrypt website at letsencrypt.org/docs, as well as the example article mentioned at the end of the chapter.
As we go through this process, I’ll first walk you through setting up TLS with a self-signed certificate so you can see how the process works. We’ll create the certificate and then install it into Apache. You won’t necessarily need to create a website to go through this process, since you could just secure the sample website that comes with Apache if you wanted something to use as a proof of concept. After we complete the process, we’ll take a look at installing certificates that were signed by a certificate authority.
To get the ball rolling, we’ll need a directory to house our certificates. I’ll use /etc/apache2/certs in my examples, although you can use whatever directory you’d like, as long as you remember to update Apache’s configuration with your desired location and filenames:
sudo mkdir /etc/apache2/certsFor a self-signed certificate and key, we can generate the pair with the following command. Feel free to change the name of the key and certificate files to match the name of your website:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/certs/mysite.key -out /etc/apache2/certs/mysite.crtYou’ll be prompted to enter some information for generating the certificate. Answer each prompt as they come along. Here’s a list of the questions you’ll be asked, along with my responses for each. Change the answers to fit your server, environment, organization name, and location:
Country Name (2 letter code) [AU]:USState or Province Name (full name) [Some-State]:MichiganLocality Name (eg, city) []:DetroitOrganization Name (eg, company) [Internet Widgits Pty Ltd]:My CompanyOrganizational Unit Name (eg, section) []:ITCommon Name (e.g. server FQDN or YOUR name) []:myserver.mydomain.comEmail Address []:[email protected]Now, you should see that two files have been created in the /etc/apache2/certs directory, mysite.crt and mysite.key, which represent the certificate and private key, respectively. Now that these files have been generated, the next thing for us to do is to configure Apache to use them. Look for the following two lines in the /etc/apache2/sites-available/default-ssl.conf file:
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pemSSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.keyComment these lines out by placing a # symbol in front of both:
# SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem# SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.keyNext, add the following two lines underneath the lines you just commented out. Be sure to replace the target directories and certificate filenames with yours, if you followed your own naming convention:
SSLCertificateFile /etc/apache2/certs/mysite.crtSSLCertificateKeyFile /etc/apache2/certs/mysite.keyTo make Apache benefit from the new configuration, reload the apache2 daemon:
sudo systemctl reload apache2With the new configuration in place, we’re not quite done but we’re close. We still have a small bit of configuration left to add. But before we get to that, let’s return to the topic of installing TLS certificates that were signed by a certificate authority. The process for installing signed TLS certificates is pretty much the same, but the main difference is how the certificate files are requested and obtained. Once you have them, you will copy them to your file server and configure Apache the same way as we just did. To start the process of obtaining a signed TLS certificate, you’ll need to create a Certificate Signing Request (CSR). A CSR is basically a request for a certificate in file form that you’ll supply to your certificate authority to start the process of requesting a signed certificate. A CSR can be easily generated with the following command:
openssl req -new -newkey rsa:2048 -nodes -keyout server.key -out server.csrWith the CSR file that was generated, you can request a signed certificate. The CSR file should now be in your current working directory. The entire process differs from one provider to another, but in most cases, it’s fairly straightforward. You’ll send them the CSR, pay their fee, fill out a form or two on their website, prove that you are the owner of the website in question, and then the vendor will send you the files you need. It may sound complicated, but certificate authorities usually walk you through the entire process and make it clear what they need from you in order to proceed. Once you complete the process, the certificate authority will send you your certificate files, which you’ll then install on your server. Once you configure the SSLCertificateFile and SSLCertificateKeyFile options in /etc/apache2/sites-available/default-ssl.conf to point to the new certificate files and reload Apache, you should be good to go.
There’s one more additional step we should perform for setting this up properly. At this point, our certificate files should be properly installed, but we’ll need to inform Apache of when to apply them. If you recall, the default-ssl.conf file provided by the apache2 package is answering requests for any traffic not otherwise identified by a virtual host (the <VirtualHost _default_:443> option). We will need to ensure that our web server is handling traffic for our existing websites when TLS is requested. We can add a ServerName option to that file to ensure our site supports TLS.
Add the following option to the /etc/apache2/sites-available/default-ssl.conf file, right underneath <VirtualHost _default_:443>:
ServerName mydomain.com:443Now, when traffic comes into your server on port 443 requesting a domain that matches the domain you typed for the ServerName option, it should result in a secure browsing session for the client. You should see the green padlock icon in the address bar (this depends on your browser), which indicates that your session is secured. If you’re using self-signed certificates, you’ll probably see an error you’ll have to skip through first, and you may not get the green padlock icon. This doesn’t mean the encryption isn’t working; it just means your browser is skeptical of the certificate since it wasn’t signed by a known certificate authority. Your session will still be encrypted.
If you are planning on hosting multiple websites over HTTPS, you may want to consider using a separate virtual host file for each. An easy way to accomplish this is to use the /etc/apache2/sites-available/default-ssl.conf file as a template and change DocumentRoot to the directory that hosts the files for that site. In addition, be sure to update the SSLCertificateFile and SSLCertificateKeyFile options to point to the certificate files for the site and set ServerName to the domain that corresponds to your site. Here’s an example virtual host file for a hypothetical site that uses TLS. I’ve highlighted lines that I’ve changed from the normal default-ssl.conf file:
<IfModule mod_ssl.c> <VirtualHost *:443> ServerName acmeconsulting.com:443
ServerAdmin webmaster@localhost
DocumentRoot /var/www/acmeconsulting ErrorLog ${APACHE_LOG_DIR}/acmeconsulting.com-error.log CustomLog ${APACHE_LOG_DIR}/acmeconsulting.com-access. log combined
SSLEngine on SSLCertificateFile /etc/apache2/certs/acmeconsulting/acme. crt SSLCertificateKeyFile /etc/apache2/certs/acmeconsulting/acme. key
<FilesMatch ".(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory>
</VirtualHost></IfModule>Basically, what I did was create a new virtual host configuration file (using the existing default-ssl.conf file as a template). I called this new file acme-consulting.conf and I stored it in the /etc/apache2/sites-available directory. I changed the VirtualHost line to listen for anything coming in on port 443. The line ServerName acmeconsulting.com:443 was added to make this file responsible for traffic coming in looking for acmeconsulting.com on port 443. I also set DocumentRoot to /var/www/acmeconsulting. In addition, I customized the error and access logs so that it will be easier to find log messages relating to this new site, since its log entries will go to their own specific files.
In my experience, I find that a modular approach, such as what I’ve done with the sample virtual host file for HTTPS, works best when setting up a web server that’s intended to host multiple websites. With each site, I’ll typically give it its own document root, certificate files, and log files. Even if you’re only planning on hosting a single site on your server, using this modular approach is still a good idea, since you may want to host additional sites later on.
So, there you have it. You should now understand how to set up secure virtual hosts in Apache.
Installing and configuring NGINX
Section titled “Installing and configuring NGINX”Apache isn’t the only technology that is capable of allowing you to host web content on your server. NGINX also serves the same purpose and is gaining popularity quite rapidly. Apache is still a great option, and even if that’s your chosen web server software, it’s a good idea to at least be familiar with NGINX and learn its basics. NGINX itself is a proxy server as well but is capable of also serving web content, which is why it competes with Apache.
Before we do so, I want to mention first that you can really only have one web server service running on a single web server. If you’ve been following along up to now, you currently have a functional Apache web server. If you were to also install NGINX, it probably wouldn’t start as the ports it wants to listen on (port 80 and/or 443) will already be in use. You can run both on a single server, but that’s outside the scope of this book. Ideally, you’d want to use one or the other. Therefore, to continue with this section you’d either want to remove Apache or set up a separate web server for testing NGINX. I recommend the latter, because later on in this chapter we will take a look at hosting Nextcloud, and we will be using Apache to do so. If you remove Apache now, you’d have to add it back in order to follow along with that section. Theoretically, you’d only have to stop the apache2 process before starting nginx, but the two resources sharing the same server have a lot of variables and may conflict.
To get started with NGINX, simply install it:
sudo apt install nginxJust like with Apache, if we enter the IP address of our server in a browser, we’re presented with a sample page, but this time NGINX’s version instead of the one that ships with Apache. It certainly looks boring in comparison, but it works:
Figure 14.3: The NGINX sample page
The default configuration files for nginx are stored in the /etc/nginx directory. Go ahead and peruse these files to get a general feel for how the configuration is presented. Similar to Apache, you also have sites-enabled and sites-available directories here, which serve the same purpose.
Just as with Apache, the sites-available directory houses configuration files for sites that can be enabled, while the sites-enabled directory stores configuration files for sites that are enabled. Unlike Apache, though, we don’t have dedicated commands to enable these sites. We have to link them manually. Although we haven’t even looked at NGINX configuration files yet, let’s just assume that we have created the following configuration file:
/etc/nginx/sites-available/acmesales.comTo enable that site, we would need to create a symbolic link for it and store that link in the /etc/nginx/sites-enabled directory:
sudo ln -s /etc/nginx/sites-available/acmesales.com /etc/nginx/sites-enabled/acmesales.comThen, we can reload nginx:
sudo systemctl reload nginxAs it stands right now, a site configuration file named default exists in /etc/nginx/sites-available and a symbolic link to it is already present in /etc/nginx/sites-enabled. If all we want to do is host a single site, we only need to replace the default content that NGINX serves, which is located in the /var/www/html directory (the same as Apache) with the content for our site. After refreshing the page, we’re good to go.
If we want to serve more than one site from one server, the default file is a great starting point for creating additional virtual hosts. We can start by copying it to a new name:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/acmesales.comObviously, acmesales.com is an example, so feel free to name this whatever you wish.
Now, we can edit this file and change it to serve additional content. First of all, only one site can be referred to as a default site. A default site in NGINX is one that answers if none of the other sites match a request. Therefore, we want to remove both occurrences of default_server from our newly copied config. Find these lines:
listen 80 default_server;listen [::]:80 default_server;Change them to this:
listen 80;listen [::]:80;Next, we’ll need to adjust the server_name option to refer to the name of our new site. Add this line:
server_name acmesales.com www.acmesales.com;Now, we’ll need to change the document root to the directory that will store the files for our new site. Find this line:
root /var/www/html;And change it to this:
root /var/www/acmesales.com;The final file should look like the following at this point:
server { listen 80; listen [::]:80;
root /var/www/acmesales.com;
index index.html index.htm index.nginx-debian.html;
server_name acmesales.com www.acmesales.com;
location / { try_files $uri $uri/ =404; }}You can probably see that the configuration format for NGINX configuration files is simpler than with Apache. I find this to be true, and I’ve noticed that sites I’ve configured with NGINX generally have fewer lines in their configuration files than Apache does.
At this point, assuming that you have the required content in /var/www/acmesales.com and have a proper configuration file, the new site should respond as soon as you reload nginx. But what about TLS? I recommend that we always secure our websites, regardless of which solution we’re using to serve it. With NGINX, we can add that feature easily. The certificate files themselves are the same regardless of whether we’re using Apache or NGINX. If you haven’t already created your certificate files, refer back to the section in this chapter where we did so. Assuming you already have certificate files, we just need to make additional changes to our configuration.
First, we change the first two lines to listen on port 443 with TLS instead of standard port 80:
listen 443 ssl;listen [::]:443 ssl;Next, we’ll add the following two lines before the location section:
ssl_certificate /etc/certs/cert.pem;ssl_certificate_key /etc/certs/cert.key;ssl_session_timeout 5m;For this to work, you’ll need to adjust the paths and the names of the cert files to make sure they match what you called them on your server. The entire file should look similar to the following at this point:
server { listen 443 ssl; listen [::]:443 ssl;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name acmesales.com www.acmesales.com;
ssl_certificate /etc/certs/cert.pem; ssl_certificate_key /etc/certs/cert.key; ssl_session_timeout 5m; location / { try_files $uri $uri/ =404; }}Finally, a potential problem is that users may access our site via port 80, instead of utilizing HTTPS. We can tell NGINX to forward these people to the secure version of our site automatically. To do that, we can edit the default configuration file (/etc/nginx/sites-available/default) and add the following line just after the two listen directives:
return 301 https://$host$request_uri;Now, anytime a user visits the HTTP version of our site, they’ll be redirected to the secure HTTPS version automatically.
Now that we’ve looked at serving web content with both Apache and NGINX, let’s take a look at setting up our very own Nextcloud server.
Setting up and configuring Nextcloud
Section titled “Setting up and configuring Nextcloud”I figured we’d end this chapter with a fun activity: setting up our very own Nextcloud server. Nextcloud is a very useful web application that’s handy for any organization. Even if you’re not working on a company network, Nextcloud is a great asset for even a single user. You can use it to synchronize files between machines, store and sync contacts, keep track of tasks you’re working on, fetch email from a mail server, and more. To complete this activity, you’ll need a web server to work with. Nextcloud supports multiple different web server platforms, but in this example, we’ll be using Apache.
You’ll also need an installation of MySQL or MariaDB, as Nextcloud will need its own database. We went over installing and managing MariaDB databases in Chapter 13, Managing Databases. I’ll give you all the commands you’ll need to set up the database in this section, but refer back to Chapter 13, Managing Databases, if any of these commands confuse you.
To get started, we need to download Nextcloud. To do so, head on over to the project’s website at https://www.nextcloud.com and navigate to the Download section. The layout of this site may change from time to time, but at the time of writing, the first link to click on is a button labeled Get Nextcloud, which will take you to the download page. As of the time of writing, the direct URL for the download page for Nextcloud is currently https://nextcloud.com/install.
Once there, look for the Archive File heading, and expand it. Underneath that, you should see a button that reads Download for Server, but don’t click on it just yet. Instead, right-click on it and click Copy link address or a similarly named option, depending on the browser you use.
This should copy the link for the download to your clipboard. If the Nextcloud website layout has changed since publication, you’re essentially just looking for the URL to the ZIP file to download Nextcloud, and you’ll want to copy it to your computer’s clipboard.
Next, open an SSH session to your web server. Make sure you’re currently working from your home directory, and execute the following command:
wget <URL of Nextcloud>To get the Nextcloud URL, simply paste the URL into your terminal after typing wget. Your entire command will look similar to the following:
wget https://download.nextcloud.com/server/releases/latest.zipThis command will download the Nextcloud software locally to your current working directory. Next, we’ll need to unzip the archive:
unzip latest.zipIf you get an error message insinuating that the unzip command is not available, you may need to install it:
sudo apt install unzipNow, let’s move the newly extracted nextcloud directory to /var/www/html:
sudo mv nextcloud /var/www/html/nextcloudIn order for Nextcloud to function, the user account that Apache uses to serve content will need full access to it. Let’s use the following command to give the user www-data ownership of the nextcloud directory:
sudo chown www-data:www-data -R /var/www/html/nextcloudNow, you should have the required files for the Nextcloud software installed on the server in the /var/www/nextcloud directory. In order for this to work, though, Apache will need a configuration file that includes /var/www/nextcloud as its document root. We can create the file we need at the following location:
/etc/apache2/sites-available/nextcloud.confExample content to include in that file is as follows:
Alias /nextcloud "/var/www/html/nextcloud/"
<Directory /var/www/html/nextcloud/> Options +FollowSymlinks AllowOverride All
<IfModule mod_dav.c> Dav off </IfModule>
SetEnv HOME /var/www/html/nextcloud SetEnv HTTP_HOME /var/www/html/nextcloud</Directory>Similar to our earlier discussion on Apache, we’re adding a config file here specifically for Nextcloud that sets up an alias to point to /nextcloud to www.mydomain.com/nextcloud. Essentially, it allows Nextcloud to be reached at your domain name, plus /nextcloud added to the end. The rest of the file disables WebDAV (a means of allowing a web server to act as a file server, not needed in our case) and then enables environment variables to set HOME and HTTP_HOME to the document root for Nextcloud, which in our case is /var/www/html/nextcloud.
Next, we enable the new site:
sudo a2ensite nextcloud.confNext, we’ll need to make a change to Apache. First, we’ll need to ensure that the libapache2-mod-php8.1 package is installed since Nextcloud requires PHP, but we’ll need some additional packages as well. You can install Nextcloud’s prerequisite packages with the following command:
sudo apt install libapache2-mod-php8.1 php8.1-curl php8.1-gd php8.1-intl php8.1-mbstring php8.1-mysql php8.1-xml php8.1-zipNext, restart Apache so that it can take advantage of the new PHP plugin:
sudo systemctl restart apache2At this point, we’ll need a MySQL or MariaDB database for Nextcloud to use. This database can exist on another server, or you can share it on the same server you installed Nextcloud on. If you haven’t already set up MariaDB, a walk-through was covered during Chapter 13, Managing Databases. At this point, it’s assumed that you already have MariaDB installed and running.
Log in to your MariaDB instance as your root user, or a user with full root privileges. You can create the Nextcloud database with the following command:
CREATE DATABASE nextcloud;Next, we’ll need to add a new user to MariaDB for Nextcloud and give that user full access to the nextcloud database. We can take care of both with the following command:
GRANT ALL ON nextcloud.* to 'nextcloud'@'localhost' IDENTIFIED BY 'super_secret_password';Make sure to change super_secret_password to a very strong (preferably randomly generated) password. Make sure you save this password in a safe place.
Now we have all we need in order to configure Nextcloud. You should now be able to visit your Nextcloud instance in a web browser. Just enter a URL similar to the following, replacing the sample IP address with the one for your server:
http://172.16.250.133/nextcloudIf you’re using a subdomain and gave Nextcloud its own virtual host, that URL would then be something like this:
http://nextcloud.yourdomain.com/nextcloudYou should see a page asking you to configure Nextcloud:

Figure 14.4: Nextcloud configuration page
If you do not see this page, make sure that the /var/www/html/nextcloud directory is accessible via Apache. Also, make sure you have an appropriate virtual host for Nextcloud referencing this directory as its Document Root.
This page will ask you for several pieces of information. First, you’ll see Username and Password. This is not asking you for a pre-existing account, but actually to set up a brand-new administrator account. This shouldn’t be an account you’ll use on a day-to-day basis, but instead an admin account you’ll use only when you want to add users and maintain your system. Please note that it won’t ask you to confirm the password, so you’ll want to make certain you’re entering the password you think you are. It’s perhaps safer to type the password in a text editor, and then copy and paste the password into the Password box to make sure you don’t lock yourself out.
Data folder will default to /var/www/html/nextcloud/data. This default is normally fine, but if you have configured your server to have a separate data partition, you can configure that here. If you plan on storing a large amount of data on your Nextcloud server, setting up a separate partition for it may be a good idea. If you do, you can set that here. Otherwise, leave the default.
In the next section, you’ll be asked to fill in information for the Nextcloud database we created earlier. Database user and Database password will use the values we created when we set up the MariaDB database for Nextcloud earlier. In my examples, I used nextcloud for the username as well as Database name. The password will be whatever it is you used for the password when we set up the database user account and granted privileges. Finally, the database server defaults to localhost, which is correct as long as you set up the database on the same machine as the Nextcloud server. If not, enter the address of your database server here, if it’s somewhere else. The following screenshot shows the initial form completely filled out with the example values we’ve used so far in this section:

Figure 14.5: Nextcloud configuration page
That’s it! Assuming all went well, Nextcloud will set itself up in the background and you’ll then continue to the main screen. Since you only created an admin account so far, I recommend you create an account for yourself, as well as any friends or colleagues you’d like to check out your Nextcloud server. To do so, go to the top-right corner of the Nextcloud page, where it shows an icon that resembles a gear. When you click on this icon, you’ll see an option for Users:

Figure 14.6: Nextcloud menu
On the Users screen, you’ll be able to add additional users to access Nextcloud. Click on the New User button. Simply fill out the Username and Password fields at the top of the screen, and then click on the blue checkmark icon to finish the process:

Figure 14.7: Adding a new user to Nextcloud
As an administrative user, you can enable or disable various apps that are used by your users. Out of the box, Nextcloud has a basic suite of apps enabled, such as the File Sharing and Photos plugins. There are many more apps that you can enable in order to extend its functionality. In the top-right corner of the main screen of Nextcloud, you’ll find an icon that looks like a gear, and if you click on it, you will find a link to Apps, which will allow you to add additional functionality. Feel free to enable additional apps to extend Nextcloud’s capabilities. Some of my must-haves include Notes and Tasks.
Now, you have your very own Nextcloud server. I find Nextcloud to be a very useful platform. Some Linux desktop environments (such as GNOME) have built-in integrations that allow you to add your Nextcloud account right to your desktop, which will allow calendar and contact syncing with your computer. There are also standalone client apps available for Linux, Windows, and macOS that you can download from the same URL that we’ve downloaded Nextcloud itself from.
I’m sure you’ll agree that Nextcloud is a very useful asset to have available. For more information on using Nextcloud, check out the manual. In fact, it’s available in the Files app from within the application itself.
Summary
Section titled “Summary”In this action-packed chapter, we looked at serving web pages with Apache. We started out by installing and configuring Apache, and then added additional modules. We also covered the concept of virtual hosts, which allow us to serve multiple websites on a single server, even if we only have a single network interface. Then, we walked through securing our Apache server with TLS. With Apache, we can use self-signed certificates, or we can purchase TLS certificates from a vendor for a fee. We looked at both possibilities. We even set up NGINX, which is a very powerful application that is growing in popularity. Finally, we closed out the chapter with a guide to installing Nextcloud, which is an application I’m sure you’ll find incredibly useful.
In the next chapter of our journey, we’ll take a look at the process of automating server configuration with Ansible, which is a lot of fun.
Relevant videos
Section titled “Relevant videos”- Nextcloud setup walk-through: https://linux.video/nextcloud-setup
Further reading
Section titled “Further reading”- NGINX documentation: https://nginx.org/en/docs/
- NGINX documentation from the Ubuntu community wiki: https://help.ubuntu.com/community/Nginx
- Apache HTTP server documentation: https://httpd.apache.org/docs/
- Nextcloud administration manual: https://docs.nextcloud.com/server/latest/admin_manual/
- Certbot instructions: https://certbot.eff.org/instructions