How To Create a Self-Signed SSL Certificate for Apache in Ubuntu 18.04

Step 1 – Creating the SSL Certificate

We can create a self-signed key and certificate pair with OpenSSL in a single command:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

Fill out the prompts appropriately. The most important line is the one that requests the Common Name (e.g. server FQDN or YOUR name). You need to enter the domain name associated with your server or, more likely, your server's public IP address.

The entirety of the prompts will look something like this:

Country Name (2 letter code) [AU]:IN

State or Province Name (full name) [Some-State]:Rajasthan

Locality Name (eg, city) []:Jaipur

Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bank of Rajasthan

Organizational Unit Name (eg, section) []:Reserve Bank of India

Common Name (e.g. server FQDN or YOUR name) []:domain_name_or_IP

Email Address []:mail@example.com

Both of the files you created will be placed in the appropriate subdirectories under /etc/ssl.

Step 2 – Configuring Apache to Use SSL

Creating an Apache Configuration Snippet with Strong Encryption Settings

Create a new snippet in the /etc/apache2/conf-available directory. We will name the file ssl-params.conf to make its purpose clear:

vi /etc/apache2/conf-available/ssl-params.conf

install creating_an_apache_config_snippet

Paste the configuration into the ssl-params.conf file we opened:

SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH

SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1

SSLHonorCipherOrder On

# Disable preloading HSTS for now.  You can use the commented out header line that includes
# the "preload" directive if you understand the implications.

# Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

Header always set X-Frame-Options DENY

Header always set X-Content-Type-Options nosniff

# Requires Apache >= 2.4

SSLCompression off

SSLUseStapling on

SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

# Requires Apache >= 2.4.11

SSLSessionTickets Off

Save and close the file when you are finished.

Modifying the Default Apache SSL Virtual Host File

Before we go any further, let's back up the original SSL Virtual Host file:

sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak

install modifying_default_apache_ssl

Now, open the SSL Virtual Host file to make adjustments:

sudo nano /etc/apache2/sites-available/default-ssl.conf

install modifying_default_apache_ssl

Inside, with most of the comments removed, the Virtual Host file should look something like this by default:

<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 will be making some minor adjustments to the file. We will set the normal things we'd want to adjust in a Virtual Host file (ServerAdmin email address, ServerName, etc., and adjust the SSL directives to point to our certificate and key files.

After making these changes, your server block should look similar to this:

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
            ServerAdmin your_email@example.com
            ServerName server_domain_or_IP

            DocumentRoot /var/www/html

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

            SSLEngine on

            SSLCertificateFile      /etc/ssl/certs/apache-selfsigned.crt
            SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

            <FilesMatch "\.(cgi|shtml|phtml|php)$">
                            SSLOptions +StdEnvVars
            </FilesMatch>
            <Directory /usr/lib/cgi-bin>
                            SSLOptions +StdEnvVars
            </Directory>

    </VirtualHost>
</IfModule>

Save and close the file when you are finished.

(Recommended) Modifying the HTTP Host File to Redirect to HTTPS

To adjust the unencrypted Virtual Host file to redirect all traffic to be SSL encrypted, we can open the /etc/apache2/sites-available/000-default.conf file:

vi /etc/apache2/sites-available/000-default.conf

install modifying_http_host_file

Inside, within the VirtualHost configuration blocks, we need to add a Redirect directive, pointing all traffic to the SSL version of the site:

<VirtualHost *:80>
    . . .

    Redirect "/" "https://your_domain_or_IP/"

    . . .
</VirtualHost>

Save and close the file when you are finished.

Step 3 – Adjusting the Firewall

We can see the available profiles by typing:

sudo ufw app list

You should see a list like this:

install Adjusting_the_Firewall

You can see the current setting by typing:

sudo ufw status

To additionally let in HTTPS traffic, we can allow the "Apache Full" profile and then delete the redundant "Apache" profile allowance:

sudo ufw allow 'Apache Full'

sudo ufw delete allow 'Apache'

Your status should look like this now:

sudo ufw enable

sudo ufw status

install Adjusting_the_Firewall

Step 4 – Enabling the Changes in Apache

We can enable mod_ssl, the Apache SSL module, and mod_headers, needed by some of the settings in our SSL snippet, with the a2enmod command:

sudo a2enmod ssl

install Enabling_the_Changes_in_Apache

sudo a2enmod headers

install Enabling_the_Changes_in_Apache

Next, we can enable our SSL Virtual Host with the a2ensite command:

sudo a2ensite default-ssl

install Enabling_the_Changes_in_Apache

We will also need to enable our ssl-params.conf file, to read in the values we set:

sudo a2enconf ssl-params

install Enabling_the_Changes_in_Apache

At this point, our site and the necessary modules are enabled. We should check to make sure that there are no syntax errors in our files. We can do this by typing:

sudo apache2ctl configtest

If everything is successful, you will get a result that looks like this:

install Enabling_the_Changes_in_Apache

If your output has Syntax OK in it, your configuration file has no syntax errors. We can safely restart Apache to implement our changes:

sudo systemctl restart apache2

install Enabling_the_Changes_in_Apache

Step 5 – Testing Encryption

Open your web browser and type https:// followed by your server's domain name or IP into the address bar:

https://your_domain_or_IP

Because the certificate we created isn't signed by one of your browser's trusted certificate authorities, you will likely see a scary looking warning.

This is expected and normal. We are only interested in the encryption aspect of our certificate, not the third party validation of our host's authenticity. Click "ADVANCED" and then the link provided to proceed to your host anyways:

You should be taken to your site. If you look in the browser address bar, you will see a lock with an "x" over it. In this case, this just means that the certificate cannot be validated. It is still encrypting your connection.

If you configured Apache to redirect HTTP to HTTPS, you can also check whether the redirect functions correctly:

http://your_domain_or_IP

If this results in the same icon, this means that your redirect worked correctly.

Step 6 – Changing to a Permanent Redirect

Open your server block configuration file again:

vi /etc/apache2/sites-available/000-default.conf

install Changing_to_a_Permanent_Redirect

Find the Redirect line we added earlier. Add permanent to that line, which changes the redirect from a 302 temporary redirect to a 301 permanent redirect:

<VirtualHost *:80>
    . . .

    Redirect permanent "/" "https://your_domain_or_IP/"

    . . .
</VirtualHost>

Save and close the file.

Check your configuration for syntax errors:

sudo apache2ctl configtest

install Changing_to_a_Permanent_Redirect

When you're ready, restart Apache to make the redirect permanent:

sudo systemctl restart apache2

install Changing_to_a_Permanent_Redirect

You have configured your Apache server to use strong encryption for client connections. This will allow you serve requests securely, and will prevent outside parties from reading your traffic.