Tutorial

How To Secure Nginx with Let's Encrypt on Ubuntu 14.04

Published on December 17, 2015
How To Secure Nginx with Let's Encrypt on Ubuntu 14.04
Not using Ubuntu 14.04?Choose a different version or distribution.
Ubuntu 14.04

Introduction

Let’s Encrypt is a new Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates, thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx web servers.

In this tutorial, we will show you how to use Certbot to obtain a free SSL certificate and use it with Nginx on Ubuntu 14.04 LTS. We will also show you how to automatically renew your SSL certificate.

We will use the default Nginx configuration file in this tutorial instead of a separate server block file. We recommend creating new Nginx server block files for each domain because it helps to avoid some common mistakes and maintains the default files as a fallback configuration as intended. If you want to set up SSL using server blocks instead, you can follow this Nginx server blocks with Let’s Encrypt tutorial.

Prerequisites

Before following this tutorial, you’ll need a few things.

  • An Ubuntu 14.04 server with a non-root user who has sudo privileges. You can learn how to set up such a user account by following our initial server setup for Ubuntu 14.04 tutorial.
  • Nginx installed, How To Install Nginx on Ubuntu 14.04 LTS
  • You must own or control the registered domain name that you wish to use the certificate with. If you do not already have a registered domain name, you may register one with one of the many domain name registrars out there (e.g. Namecheap, GoDaddy, etc.).
  • A DNS A Record that points your domain to the public IP address of your server. You can follow this hostname tutorial for details on how to add them. This is required because of how Let’s Encrypt validates that you own the domain it is issuing a certificate for. For example, if you want to obtain a certificate for example.com, that domain must resolve to your server for the validation process to work. Our setup will use example.com and www.example.com as the domain names, so both DNS records are required.

Once you have all of the prerequisites out of the way, let’s move on to installing Certbot, the Let’s Encrypt client software.

Step 1 — Installing Certbot

The first step to using Let’s Encrypt to obtain an SSL certificate is to install the certbot software on your server. The Certbot developers maintain their own Ubuntu software repository with up-to-date versions of the software. Because Certbot is in such active development it’s worth using this repository to install a newer Certbot than provided by Ubuntu.

First, add the repository:

  1. sudo add-apt-repository ppa:certbot/certbot

You’ll need to press ENTER to accept. Afterwards, update the package list to pick up the new repository’s package information:

  1. sudo apt-get update

And finally, install Certbot with apt-get:

  1. sudo apt-get install python-certbot-nginx

The certbot Let’s Encrypt client is now ready to use.

Step 2 — Setting up Nginx

Certbot can automatically configure SSL for Nginx, but it needs to be able to find the correct server block in your config. It does this by looking for a server_name directive that matches the domain you’re requesting a certificate for. If you’re starting out with a fresh Nginx install, you can update the default config file:

  1. sudo nano /etc/nginx/sites-available/default

Find the existing server_name line:

/etc/nginx/sites-available/default
server_name localhost;

Replace localhost with your domain name:

/etc/nginx/sites-available/default
server_name example.com www.example.com;

Save the file and quit your editor. Verify the syntax of your configuration edits with:

  1. sudo nginx -t

If that runs with no errors, reload Nginx to load the new configuration:

  1. sudo service nginx reload

Certbot will now be able to find the correct server block and update it. Now we’ll update our firewall to allow HTTPS traffic.

Step 3 — Obtaining an SSL Certificate

Certbot provides a variety of ways to obtain SSL certificates, through various plugins. The Nginx plugin will take care of reconfiguring Nginx and reloading the config whenever necessary:

  1. sudo certbot --nginx -d example.com -d www.example.com

This runs certbot with the --nginx plugin, using -d to specify the names we’d like the certificate to be valid for.

If this is your first time running certbot, you will be prompted to enter an email address and agree to the terms of service. After doing so, certbot will communicate with the Let’s Encrypt server, then run a challenge to verify that you control the domain you’re requesting a certificate for.

If that’s successful, certbot will ask how you’d like to configure your HTTPS settings:

Output
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):

Select your choice then hit ENTER. The configuration will be updated, and Nginx will reload to pick up the new settings. certbot will wrap up with a message telling you the process was successful and where your certificates are stored:

Output
IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at /etc/letsencrypt/live/example.com/fullchain.pem. Your cert will expire on 2017-10-23. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le

Your certificates are now downloaded, installed, and configured. Try reloading your website using https:// and notice your browser’s security indicator. It should represent that the site is properly secured, usually with a green lock icon. If you test your server using the SSL Labs Server Test, it will get an A grade.

Step 4 — Verifying Certbot Auto-Renewal

Let’s Encrypt’s certificates are only valid for ninety days. This is to encourage users to automate their certificate renewal process. The certbot package we installed takes care of this for us by running ‘certbot renew’ twice a day via a systemd timer. On non-systemd distributions this functionality is provided by a script placed in /etc/cron.d. This task runs twice a day and will renew any certificate that’s within thirty days of expiration.

To test the renewal process, you can do a dry run with certbot:

  1. sudo certbot renew --dry-run

If you see no errors, you’re all set. When necessary, Certbot will renew your certificates and reload Nginx to pick up the changes. If the automated renewal process ever fails, Let’s Encrypt will send a message to the email you specified, warning you when your certificate is about to expire.

Conclusion

In this tutorial we’ve installed the Let’s Encrypt client certbot, downloaded SSL certificates for our domain, configured Nginx to use these certificates, and set up automatic certificate renewal. If you have further questions about using Certbot, their documentation is a good place to start.

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

Learn more about us


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 article, and you were crazy-fast with the publication - a jiffy after the public beta is out. Kudos!

Great article, thanks !

I guess there is a little mistake here :

30 2 * * 1 /usr/sbin/le-renew-webroot >> /var/log/le-renewal.log

It should be

30 2 * * 1 /usr/local/sbin/le-renew-webroot >> /var/log/le-renewal.log

i’m having errors, I believe it’s because my nginx configuration (from the one-click-app drupal install) blocks hidden directories. Could you perhaps add a block to the nginx configuration that allows the .well-known/acme-challenge directory

Line

netstat -na | 'grep :80.*LISTEN'

should be

netstat -na | grep ':80.*LISTEN'

Thanks, Mitchell! This article was great. I had set up my server with Flask (https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-16-04), so I had to change Steps 2 and 3 a little.

Step 2: Instead of changing /etc/nginx/sites-available/default, I added the following function to my main Python file at ~/ProjectName/ProjectName.py:

@app.route('/.well-known/acme-challenge/<token_value>')
def letsencrpyt(tmp):
    with open('.well-known/acme-challenge/{}'.format(token_value)) as f:
        answer = f.readline().strip()
    return answer

Source: https://hjlog.me/post/177

Step 3: Instead of changing /etc/nginx/sites-available/default, I added the SSL information and new server block to my project’s configuration file: /etc/nginx/sites-available/ProjectName.

WARNING: THE AUTO UPDATE WILL NO LONGER WORK ACCORDING TO THIS GUIDE

letsencrypt-auto has been replaced with Certbot (https://certbot.eff.org/#ubuntutrusty-nginx). You might see a warning about this, but it doesn’t make it clear that letsencrypt-auto does not work. Worse still you may still receive a success message when attempting an update with letsencryt-auto (I was getting the congrats message but my certs weren’t actually updating) - so you may not see any errors, and the crontab job will succeed (this is how I missed the issue until my certs actually expired this morning… on a Sunday).

An update to this guide with this in mind would be great - as although I’ve restored my certs I’m not sure how to work Certbot into the auto-renew process with crontab.

I need to publish both 80 and 443 ports in a docker container in order to successfuly build the certs. Is it missed in the tutorial (in verfy ports open section) or am I doing something wrong?

This is great - thank you very much! It helped me a lot… :)

You may want to add in ‘Nginx configuration additions — 3 of 3’ your domain with www before (to prevent errors in the renewal step):

    server_name example.com www.example.com;

Also I had to install bc to make your script work:

sudo apt-get install bc

First of all, thank you for this very nice article! I used this on a Centos 7.2 box and it worked like a charm!

I ran into an ‘issue’, I got only a B at SSL labs using this configuration. I fixed it by generating a custom diffie hellman 2048 primes set as described on this page.

https://weakdh.org/sysadmin.html

Maybe you can update your guide with this, if you find it relevant.

The ./letsencrypt-auto certonly --standalone command seems to fail, telling me that the domain name contains invalid characters.

I believe this is supposed to be: ./letsencrypt-auto certonly --standalone -d example.com

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!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

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

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel