Tutorial

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

How To Create a Self-Signed SSL Certificate for Apache in Ubuntu 16.04
Not using Ubuntu 16.04?Choose a different version or distribution.
Ubuntu 16.04

Introduction

TLS, or transport layer security, and its predecessor SSL, which stands for secure sockets layer, are web protocols used to wrap normal traffic in a protected, encrypted wrapper.

Using this technology, servers can send traffic safely between the server and clients without the possibility of the messages being intercepted by outside parties. The certificate system also assists users in verifying the identity of the sites that they are connecting with.

In this guide, you will learn how to set up a self-signed SSL certificate for use with an Apache web server on an Ubuntu 16.04 server.

Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers and operating systems, users cannot use the certificate to validate the identity of your server automatically. As a result, your users will see a security error when visiting your site.

Because of this limitation, self-signed certificates are not appropriate for a production environment serving the public. They are typically used for testing, or for securing non-critical services used by a single user or a small group of users that can establish trust in the certificate’s validity through alternate communication channels.

For a more production-ready certificate solution, check out Let’s Encrypt, a free certificate authority. You can learn how to download and configure a Let’s Encrypt certificate in our How To Secure Apache with Let’s Encrypt on Ubuntu 16.04 tutorial.

Prerequisites

Before starting this tutorial, you’ll need the following:

  • Access to a Ubuntu 16.04 server with a non-root, sudo-enabled user. Our Initial Server Setup with Ubuntu 16.04 guide can show you how to create this account.

  • You will also need to have Apache installed. You can install Apache using apt. First, update the local package index to reflect the latest upstream changes:

    1. sudo apt update

    Then, install the apache2 package:

    1. sudo apt install apache2

    And finally, if you have a ufw firewall set up, open up the http and https ports:

    1. sudo ufw allow "Apache Full"

After these steps are complete, be sure you are logged in as your non-root user and continue with the tutorial.

Step 1 — Enabling mod_ssl

Before we can use any SSL certificates, we first have to enable mod_ssl, an Apache module that provides support for SSL encryption.

Enable mod_ssl with the a2enmod command:

  1. sudo a2enmod ssl

Restart Apache to activate the module:

  1. sudo systemctl restart apache2

The mod_ssl module is now enabled and ready for use.

Step 2 — Create the SSL Certificate

Now that Apache is ready to use encryption, we can move on to generating a new SSL certificate. The certificate will store some basic information about your site, and will be accompanied by a key file that allows the server to securely handle encrypted data.

We can create the SSL key and certificate files with the openssl command:

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

After you enter the command, you will be taken to a prompt where you can enter information about your website. Before we go over that, let’s take a look at what is happening in the command we are issuing:

  • openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files.
  • req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The “X.509” is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. We want to create a new X.509 cert, so we are using this subcommand.
  • -x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed certificate instead of generating a certificate signing request, as would normally happen.
  • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Apache to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening because we would have to enter it after every restart.
  • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here.
  • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
  • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
  • -out: This tells OpenSSL where to place the certificate that we are creating.

As we stated above, these options will create both a key file and a certificate. We will be asked a few questions about our server in order to embed the information correctly in the certificate.

Fill out the prompts appropriately. The most important line is the one that requests the Common Name. You need to enter either the hostname you’ll use to access the server by, or the public IP of the server. It’s important that this field matches whatever you’ll put into your browser’s address bar to access the site, as a mismatch will cause more security errors.

The entirety of the prompts will look something like this:

Country Name (2 letter code) [XX]:US
State or Province Name (full name) []:Example
Locality Name (eg, city) [Default City]:Example 
Organization Name (eg, company) [Default Company Ltd]:Example Inc
Organizational Unit Name (eg, section) []:Example Dept
Common Name (eg, your name or your server's hostname) []:your_domain_or_ip
Email Address []:webmaster@example.com

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

Step 3 — Configure Apache to Use SSL

Now that we have our self-signed certificate and key available, we need to update our Apache configuration to use them. On Ubuntu, you can place new Apache configuration files (they must end in .conf) into /etc/apache2/sites-available/and they will be loaded the next time the Apache process is reloaded or restarted.

For this tutorial we will create a new minimal configuration file. (If you already have an Apache <Virtualhost> set up and just need to add SSL to it, you will likely need to copy over the configuration lines that start with SSL, and switch the VirtualHost port from 80 to 443. We will take care of port 80 in the next step.)

Open a new file in the /etc/apache2/sites-available directory:

  1. sudo nano /etc/apache2/sites-available/your_domain_or_ip.conf

Paste in the following minimal VirtualHost configuration:

/etc/apache2/sites-available/your_domain_or_ip.conf
<VirtualHost *:443>
   ServerName your_domain_or_ip
   DocumentRoot /var/www/your_domain_or_ip

   SSLEngine on
   SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
   SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
</VirtualHost>

Be sure to update the ServerName line to however you intend to address your server. This can be a hostname, full domain name, or an IP address. Make sure whatever you choose matches the Common Name you chose when making the certificate.

The remaining lines specify a DocumentRoot directory to serve files from, and the SSL options needed to point Apache to our newly-created certificate and key.

Now let’s create our DocumentRoot and put an HTML file in it just for testing purposes:

  1. sudo mkdir /var/www/your_domain_or_ip

Open a new index.html file with your text editor:

  1. sudo nano /var/www/your_domain_or_ip/index.html

Paste the following into the blank file:

/var/www/your_domain_or_ip/index.html
<h1>it worked!</h1>

This is not a full HTML file, of course, but browsers are lenient and it will be enough to verify our configuration.

Save and close the file Next, we need to enable the configuration file with the a2ensite tool:

  1. sudo a2ensite your_domain_or_ip.conf

It will prompt you to restart Apache to activate the configuration, but first, let’s test for configuration errors:

  1. sudo apache2ctl configtest

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

Output
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK

The first line is a message telling you that the ServerName directive is not set globally. If you want to get rid of that message, you can set ServerName to your server’s domain name or IP address in /etc/apache2/apache2.conf. This is optional as the message will do no harm.

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

  1. sudo systemctl reload apache2

Now load your site in a browser, being sure to use https:// at the beginning.

You should see an error. This is normal for a self-signed certificate! The browser is warning you that it can’t verify the identity of the server, because our certificate is not signed by any of its known certificate authorities. For testing purposes and personal use this can be fine. You should be able to click through to advanced or more information and choose to proceed.

After you do so, your browser will load the it worked! message.

Note: if your browser doesn’t connect at all to the server, make sure your connection isn’t being blocked by a firewall. If you are using ufw, the following commands will open ports 80 and 443:

  1. sudo ufw allow "Apache Full"

Next we will add another VirtualHost section to our configuration to serve plain HTTP requests and redirect them to HTTPS.

Step 4 — Redirecting HTTP to HTTPS

Currently, our configuration will only respond to HTTPS requests on port 443. It is good practice to also respond on port 80, even if you want to force all traffic to be encrypted. Let’s set up a VirtualHost to respond to these unencrypted requests and redirect them to HTTPS.

Open the same Apache configuration file we started in previous steps:

  1. sudo nano /etc/apache2/sites-available/your_domain_or_ip.conf

At the bottom, create another VirtualHost block to match requests on port 80. Use the ServerName directive to again match your domain name or IP address. Then, use Redirect to match any requests and send them to the SSL VirtualHost. Make sure to include the trailing slash:

/etc/apache2/sites-available/your_domain_or_ip.conf
<VirtualHost *:80>
    ServerName your_domain_or_ip
    Redirect / https://your_domain_or_ip/
</VirtualHost>

Save and close this file when you are finished, then test your configuration syntax again, and reload Apache:

  1. sudo apachectl configtest
  2. sudo systemctl reload apache2

You can test the new redirect functionality by visiting your site with plain http:// in front of the address. You should be redirected to https:// automatically.

Conclusion

You have now configured Apache to serve encrypted requests using a self-signed SSL certificate, and to redirect unencrypted HTTP requests to HTTPS.

If you are planning on using SSL for a public website, you should look into purchasing a domain name and using a widely supported certificate authority such as Let’s Encrypt.

For more information on using Let’s Encrypt with Apache, please read our How To Secure Apache with Let’s Encrypt on Ubuntu 16.04 tutorial.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Great tutorial; lots of details & easy to follow. Probably should mention we can avoid using self-signed certs, and use Let’sEncrypt CA.

I’ve used this on all of the Ubuntu servers I’ve deployed and in a custom installation script for an Ubuntu based ownCloud server.

The ownCloud server brought something to my attention: the ssl-params.conf file is never enabled. It does not show in conf-enabled after completing an install, and ownCloud complains about the max-age setting not being enabled.

How is the .conf file being accessed by Apache or the SSL mod to pull the settings for use?

I’ve taught myself Linux and bash scripting over the course of three months while developing that installation script (it automates nearly every aspect of a 20 page walk-through I wrote for configuring the server based on very high security standards), so I may be making a noob mistake.

Why am I getting the following error?

AH00526: Syntax error on line 12 of /etc/apache2/conf-enabled/ssl-params.conf:
Invalid command 'SSLSessionTickets', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.

Hello,

I am getting this kind of error : Could you help to identify the issue ?

AH00526: Syntax error on line 12 of /etc/apache2/conf-enabled/ssl-params.conf:
Invalid command 'SSLSessionTickets', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.

I generally appreciate the clarity of your explanations; this is a definite +!

However, I would need to move one step beyond the " Redirect “/” “https://your_domain_or_IP”" line, which works perfectly from the Internet to my web server, but not from clients on the same LAN as the server.

Can I branch to something like "Redirect “/” “https://my_server_local_IP” by detecting the origin of the client IP or else?

Just Subscribed in order to leave comment. First, thank you for this one and the rest of tutorials on your website.

I have a file upload/sharing website and after i followed your tutorial i have had a few issues (having to update my apache because of certain rules in ssl-params, i was on Ubuntu 15.10, had to do an upgrade on my server over ssh, which failed at some point because of mysql 5.7 being not able to have blank port with phpmyadmin, well it was painful but at some point i managed to do the upgrade) but the biggest one was the “remote url upload”, Curl, which was not working anymore. I have checked all sort of things to disable verify_peer and verify_host but found that my file sharing script had already a false status on those. I was kinda lost and at some point i remember we had applied security parameters in ssl-params from a thirdparty that you were sharing here but that they could be the faulty ones. I tried to do an sudo a2disconf ssl-params, restartedapache and BINGO, it was working again. I then commented re-enable the ssl-params conf and isolated the faulty rule after commenting all of them one after the other. I’m here to share my finding, the faulty rule is

Header always set X-Frame-Options DENY

So in Shorter terms,

Comment this rule in /etc/apache2/conf-available/ssl-params.conf

#Header always set X-Frame-Options DENY

If you need CURL to work with this tutorial.

Thanks.

I had hard time to understand the difference between a Self-Signed SSL certificate and a CA one, despite your yellow information note (sorry I am a beginner :).

So here the stackoverflow answer on the matter that helped me to clearly understand the point:

The SSL certificate solves two purposes: encryption of traffic (for RSA key exchange, at least) and verification of trust. As you know, you can encrypt traffic with (or without, if we’re talking SSL 3.0 or TLS) any self-signed certificate. But trust is accomplished through a chain of certificates. I don’t know you, but I do trust verisign (or at least Microsoft does, because they’ve been paid lots of money to get it installed in their operating systems by default), and since Verisign trusts you, then I trust you too. As a result, there’s no scary warning when I go to such an SSL page in my Web browser because somebody that I trust has said you are who you are.

More: http://stackoverflow.com/questions/292732/self-signed-ssl-cert-or-ca

Great and easy understandable tutorial. Thank you for the invested time on writing it.

I´ve did all as you well describe on the tutorial, however now I´m facing an issue I´d like to know how to solve.

Despite it works and I´m able to access via HTTPS https://www.camarahispano-turca.org/

would like to know how to switch the “red warning” icon into the trustable “green shield” one

thanks for being patient since I´m newbie on all this server issues

First of all, thank you @justin for your great and easily understandable tutorial. It helps me a lot.

I´ve followed and did all you said on it and finally I achieved to connect the site via HTTPS [https://www.camarahispano-turca.org]

However, I´m not sure how I should do to get switch the “red warning” icon into the “green shield” one more trustable

Looking forward to hear from you

So I have no Idea what I’m doing wrong, I’m getting a redirect loop when trying to go thru this guide with a domain name. Is that my problem? Should I just use the Let’sEncrypt service instead?

The weirdest part to is on part 4, it says that the syntax is OK. Could it be that I’m using CloudFlare as DNS?

Could you clarify how your 000-default.conf File looks? As that seems to be my problem… Have you done this with a domain name instead of ip?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.