// Tutorial //

How To Secure Apache with Let's Encrypt on Ubuntu 22.04

How To Secure Apache with Let's Encrypt on Ubuntu 22.04
Not using Ubuntu 22.04?Choose a different version or distribution.
Ubuntu 22.04

Introduction

Let’s Encrypt is a Certificate Authority (CA) that facilitates obtaining and installing free TLS/SSL certificates, thereby enabling encrypted HTTPS on web servers. It streamlines 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.

In this guide, you’ll use Certbot to obtain a free SSL certificate for Apache on Ubuntu 22.04, and make sure this certificate is set up to renew automatically.

This tutorial uses a separate virtual host file instead of Apache’s default configuration file for setting up the website that will be secured by Let’s Encrypt. We recommend creating new Apache virtual host files for each domain hosted in a server because it helps to avoid common mistakes and maintains the default configuration files as a fallback setup.

Prerequisites

To follow this tutorial, you will need:

  • One Ubuntu 22.04 server set up with a non-root user with sudo administrative privileges and firewall enabled. You can set this up by following our initial server setup for Ubuntu 22.04 tutorial.

  • A fully registered domain name. This tutorial will use your_domain as an example throughout. You can purchase a domain name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice.

  • Both of the following DNS records set up for your server. You can follow this introduction to DigitalOcean DNS for details on how to add them.

    • An A record with your_domain pointing to your server’s public IP address.
    • An A record with www.your_domain pointing to your server’s public IP address.
  • Apache installed by following How To Install Apache on Ubuntu 22.04. Be sure that you have a virtual host file for your domain. This tutorial will use /etc/apache2/sites-available/your_domain.conf as an example.

Step 1 — Installing Certbot

To obtain an SSL certificate with Let’s Encrypt, you need to install the Certbot software on your server. You’ll use the default Ubuntu package repositories for that.

First, update the local package index:

  1. sudo apt update

You need two packages: certbot, and python3-certbot-apache. The latter is a plugin that integrates Certbot with Apache, making it possible to automate obtaining a certificate and configuring HTTPS within your web server with a single command:

  1. sudo apt install certbot python3-certbot-apache

You will be prompted to confirm the installation by pressing Y, then ENTER.

Certbot is now installed on your server. In the next step, you’ll verify Apache’s configuration to make sure your virtual host is set appropriately. This will ensure that the certbot client script will be able to detect your domains and reconfigure your web server to use your newly generated SSL certificate automatically.

Step 2 — Checking your Apache Virtual Host Configuration

To automatically obtain and configure SSL for your web server, Certbot needs to find the correct virtual host within your Apache configuration files. Your server domain name(s) will be retrieved from the ServerName and ServerAlias directives defined within your VirtualHost configuration block.

If you followed the virtual host setup step in the Apache installation tutorial, you should have a VirtualHost block set up for your domain at /etc/apache2/sites-available/your_domain.conf with the ServerName and also the ServerAlias directives already set appropriately.

To confirm this is set up, open the virtual host file for your domain using nano or your preferred text editor:

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

Find the existing ServerName and ServerAlias lines. They should be listed as follows:

/etc/apache2/sites-available/your_domain.conf
...
ServerName your_domain
ServerAlias www.your_domain
...

If you already have your ServerName and ServerAlias set up like this, you can exit your text editor and move on to the next step. If your current virtual host configuration doesn’t match the example, update it accordingly. If you’re using nano, you can exit by pressing CTRL+X, then Y and ENTER to confirm your changes, if any. Then, run the following command to validate your changes:

  1. sudo apache2ctl configtest

You should receive Syntax OK as a response. If you get an error, reopen the virtual host file and check for any typos or missing characters. Once your configuration file’s syntax is correct, reload Apache so that the changes take effect:

  1. sudo systemctl reload apache2

With these changes, Certbot will be able to find the correct VirtualHost block and update it.

Next, you’ll update the firewall to allow HTTPS traffic.

Step 3 — Allowing HTTPS Through the Firewall

If you have the UFW firewall enabled, as recommended by the prerequisite guides, you’ll need to adjust the settings to allow HTTPS traffic. Upon installation, Apache registers a few different UFW application profiles. You can leverage the Apache Full profile to allow both HTTP and HTTPS traffic on your server.

To verify what kind of traffic is currently allowed on your server, check the status:

  1. sudo ufw status

If you followed one of our Apache installation guides, you will have output similar to the following, meaning that only HTTP traffic on port 80 is currently allowed:

Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6)

To allow for HTTPS traffic, allow the “Apache Full” profile:

  1. sudo ufw allow 'Apache Full'

Then delete the redundant “Apache” profile:

  1. sudo ufw delete allow 'Apache'

Your status will display as the following:

  1. sudo ufw status
Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache Full ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache Full (v6) ALLOW Anywhere (v6)

You are now ready to run Certbot and obtain your certificates.

Step 4 — Obtaining an SSL Certificate

Certbot provides a variety of ways to obtain SSL certificates through plugins. The Apache plugin will take care of reconfiguring Apache and reloading the configuration whenever necessary. To use this plugin, run the following:

  1. sudo certbot --apache

This script will prompt you to answer a series of questions in order to configure your SSL certificate. First, it will ask you for a valid email address. This email will be used for renewal notifications and security notices:

Output
Saving debug log to /var/log/letsencrypt/letsencrypt.log Enter email address (used for urgent renewal and security notices) (Enter 'c' to cancel): you@your_domain

After providing a valid email address, press ENTER to proceed to the next step. You will then be prompted to confirm if you agree to Let’s Encrypt terms of service. You can confirm by pressing Y and then ENTER:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

Next, you’ll be asked if you would like to share your email with the Electronic Frontier Foundation to receive news and other information. If you do not want to subscribe to their content, write N. Otherwise, write Y then press ENTER to proceed to the next step:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: N

The next step will prompt you to inform Certbot of which domains you’d like to activate HTTPS for. The listed domain names are automatically obtained from your Apache virtual host configuration, so it’s important to make sure you have the correct ServerName and ServerAlias settings configured in your virtual host. If you’d like to enable HTTPS for all listed domain names (recommended), you can leave the prompt blank and press ENTER to proceed. Otherwise, select the domains you want to enable HTTPS for by listing each appropriate number, separated by commas and/ or spaces, then press ENTER:

Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: your_domain
2: www.your_domain
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 

After this step, Certbot’s configuration is finished, and you will be presented with the final remarks about your new certificate and where to locate the generated files:

Output
Successfully received certificate. Certificate is saved at: /etc/letsencrypt/live/your_domain/fullchain.pem Key is saved at: /etc/letsencrypt/live/your_domain/privkey.pem This certificate expires on 2022-07-10. These files will be updated when the certificate renews. Certbot has set up a scheduled task to automatically renew this certificate in the background. Deploying certificate Successfully deployed certificate for your_domain to /etc/apache2/sites-available/your_domain-le-ssl.conf Successfully deployed certificate for www.your_domain.com to /etc/apache2/sites-available/your_domain-le-ssl.conf Congratulations! You have successfully enabled HTTPS on https:/your_domain and https://www.your_domain.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 certificate is now installed and loaded into Apache’s configuration. Try reloading your website using https:// and notice your browser’s security indicator. It should indicate that your site is properly secured, typically by a lock icon in the address bar.

You can use the SSL Labs Server Test to verify your certificate’s grade and obtain detailed information about it, from the perspective of an external service.

In the next and final step, you’ll test the auto-renewal feature of Certbot, which guarantees that your certificate will be renewed automatically before the expiration date.

Step 5 — 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, as well as to ensure that misused certificates or stolen keys will expire sooner rather than later.

The certbot package you installed takes care of renewals by including a renew script to /etc/cron.d, which is managed by a systemctl service called certbot.timer. This script runs twice a day and will automatically renew any certificate that’s within thirty days of expiration.

To check the status of this service and make sure it’s active, run the following:

  1. sudo systemctl status certbot.timer

Your output will be similar to the following:

Output
● certbot.timer - Run certbot twice daily Loaded: loaded (/lib/systemd/system/certbot.timer; enabled; vendor preset:> Active: active (waiting) since Mon 2022-04-11 20:52:46 UTC; 4min 3s ago Trigger: Tue 2022-04-12 00:56:55 UTC; 4h 0min left Triggers: ● certbot.service Apr 11 20:52:46 jammy-encrypt systemd[1]: Started Run certbot twice daily.

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

  1. sudo certbot renew --dry-run
Output
Saving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Processing /etc/letsencrypt/renewal/your_domain.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Account registered. Simulating renewal of an existing certificate for your_domain and www.your_domain.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations, all simulated renewals succeeded: /etc/letsencrypt/live/your_domain/fullchain.pem (success) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

If you don’t receive any errors, you’re all set. When necessary, Certbot will renew your certificates and reload Apache 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, you installed the Let’s Encrypt client certbot, configured and installed an SSL certificate for your domain, and confirmed that Certbot’s automatic renewal service is active within systemctl. 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


Tutorial Series: Getting Started With Cloud Computing

This curriculum introduces open-source cloud computing to a general audience along with the skills necessary to deploy applications and websites securely to the cloud.

About the authors
Default avatar

Technical Writer

Educator and writer committed to empowering our community by providing access to the knowledge and tools for making creative ideas into a reality


Default avatar

Developer Advocate

Dev/Ops passionate about open source, PHP, and Linux.


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
9 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!

Does it work if A records point to the floating IP address of the server?

Good Explanations. Thanks.

Hi there, I was trying to install certbox using the command in step one: sudo apt install certbox, but the result shows: Reading package lists… Done Building dependency tree… Done Reading state information… Done E: Unable to locate package certbox

Any idea how to install certbox?

I got the SSL for one of my domains, I also want to do the same for another domain but it doesnt appear when I run the command although I have its .conf file the same way as for first domain

any help?

Why is that?

certbot --apache

Saving debug log to /var/log/letsencrypt/letsencrypt.log An unexpected error occurred: RuntimeError: (‘Error during match procedure!’, “/files/etc/apache2/sites-enabled/* [label()=~regexp(‘(?=(?P<g0>.?\.))(?P=g0).’)]//*[self::directive=~regexp(‘([Ii][Nn][Cc][Ll][Uu][Dd][Ee])|([Ii][Nn][Cc][Ll][Uu][Dd][Ee])|([Ii][Nn][Cc][Ll][Uu][Dd][Ee][Oo][Pp][Tt][Ii][Oo][Nn][Aa][Ll])’)]”) Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details.

cat /var/log/letsencrypt/letsencrypt.log

2023-04-16 16:12:31,717:DEBUG:certbot._internal.main:certbot version: 1.21.0 2023-04-16 16:12:31,717:DEBUG:certbot._internal.main:Location of certbot entry point: /usr/bin/certbot 2023-04-16 16:12:31,717:DEBUG:certbot._internal.main:Arguments: [‘–apache’] 2023-04-16 16:12:31,718:DEBUG:certbot._internal.main:Discovered plugins: PluginsRegistry(PluginEntryPoint#apache,PluginEntryPoint#manual,PluginEntryPoint#null,PluginEntryPoint#standalone,PluginEntryPoint#webroot) 2023-04-16 16:12:31,728:DEBUG:certbot._internal.log:Root logging level set at 30 2023-04-16 16:12:31,728:DEBUG:certbot._internal.plugins.selection:Requested authenticator apache and installer apache 2023-04-16 16:12:31,787:DEBUG:certbot_apache._internal.configurator:Apache version is 2.4.52 2023-04-16 16:12:31,884:DEBUG:certbot._internal.log:Exiting abnormally: Traceback (most recent call last): File “/usr/bin/certbot”, line 33, in <module> sys.exit(load_entry_point(‘certbot==1.21.0’, ‘console_scripts’, ‘certbot’)()) File “/usr/lib/python3/dist-packages/certbot/main.py”, line 15, in main return internal_main.main(cli_args) File “/usr/lib/python3/dist-packages/certbot/_internal/main.py”, line 1574, in main return config.func(config, plugins) File “/usr/lib/python3/dist-packages/certbot/_internal/main.py”, line 1270, in run installer, authenticator = plug_sel.choose_configurator_plugins(config, plugins, “run”) File “/usr/lib/python3/dist-packages/certbot/_internal/plugins/selection.py”, line 216, in choose_configurator_plugins authenticator = installer = pick_configurator(config, req_inst, plugins) File “/usr/lib/python3/dist-packages/certbot/_internal/plugins/selection.py”, line 22, in pick_configurator return pick_plugin( File “/usr/lib/python3/dist-packages/certbot/_internal/plugins/selection.py”, line 106, in pick_plugin verified.prepare() File “/usr/lib/python3/dist-packages/certbot/_internal/plugins/disco.py”, line 297, in prepare return [plugin_ep.prepare() for plugin_ep in self._plugins.values()] File “/usr/lib/python3/dist-packages/certbot/_internal/plugins/disco.py”, line 297, in <listcomp> return [plugin_ep.prepare() for plugin_ep in self._plugins.values()] File “/usr/lib/python3/dist-packages/certbot/_internal/plugins/disco.py”, line 151, in prepare self._initialized.prepare() File “/usr/lib/python3/dist-packages/certbot_apache/_internal/configurator.py”, line 360, in prepare self.parser = self.get_parser() File “/usr/lib/python3/dist-packages/certbot_apache/_internal/configurator.py”, line 466, in get_parser return parser.ApacheParser( File “/usr/lib/python3/dist-packages/certbot_apache/_internal/parser.py”, line 67, in init self.update_runtime_variables() File “/usr/lib/python3/dist-packages/certbot_apache/_internal/parser.py”, line 279, in update_runtime_variables self.update_includes() File “/usr/lib/python3/dist-packages/certbot_apache/_internal/parser.py”, line 293, in update_includes _ = self.find_dir(“Include”) File “/usr/lib/python3/dist-packages/certbot_apache/_internal/parser.py”, line 552, in find_dir ordered_matches.extend(self.find_dir( File “/usr/lib/python3/dist-packages/certbot_apache/_internal/parser.py”, line 534, in find_dir matches = self.aug.match( File “/usr/lib/python3/dist-packages/augeas.py”, line 415, in match raise RuntimeError(“Error during match procedure!”, path) RuntimeError: (‘Error during match procedure!’, “/files/etc/apache2/sites-enabled/* [label()=~regexp(‘(?=(?P<g0>.?\.))(?P=g0).’)]//[self::directive=~regexp(‘([Ii][Nn][Cc][Ll][Uu][Dd][Ee])|([Ii][Nn][Cc][Ll][Uu][Dd][Ee])|([Ii][Nn][Cc][Ll][Uu][Dd][Ee][Oo][Pp][Tt][Ii][Oo][Nn][Aa][Ll])’)]") 2023-04-16 16:12:31,886:ERROR:certbot._internal.log:An unexpected error occurred: 2023-04-16 16:12:31,886:ERROR:certbot._internal.log:RuntimeError: (‘Error during match procedure!’, "/files/etc/apache2/sites-enabled/ [label()=~regexp(‘(?=(?P<g0>.?\.))(?P=g0).’)]//*[self::directive=~regexp(‘([Ii][Nn][Cc][Ll][Uu][Dd][Ee])|([Ii][Nn][Cc][Ll][Uu][Dd][Ee])|([Ii][Nn][Cc][Ll][Uu][Dd][Ee][Oo][Pp][Tt][Ii][Oo][Nn][Aa][Ll])’)]”)

How would one generate wildcard certificate?

I’ve been having the same problem as Angelo for over a month. I was considering leaving Linode.com and going to Digital Ocean and starting fresh. I’ve tried community.letsencrypt.org without success.

Hi,I’m using Ubuntu2.4.4 in digitalocean and I can’t add Let’s Encrypt.

Ubuntu2.4.4,Server version: Apache/2.4.52 (Ubuntu)

root@ubuntu-s-4vcpu-8gb-amd-sfo3-01:~# sudo certbot --apache
Saving debug log to /var/log/letsencrypt/letsencrypt.log

Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: 123456.com
2: www.123456.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel):
Requesting a certificate for 123456.com and www.123456.com

Certbot failed to authenticate some domains (authenticator: apache). The Certificate Authority reported these problems:
  Domain: www.123456.com
  Type:   unauthorized
  Detail: 143.198.52.216: Invalid response from http://www.123456.com/.well-known/acme-challenge/Er6_YVQrVYvxgnvxNccwLvf0ROiOim12DgyPMb7i-Ug: 503

  Domain: 123456.com
  Type:   unauthorized
  Detail: 143.198.52.216: Invalid response from http://123456.com/.well-known/acme-challenge/mfilNLCRNwPfsqgM9TyIwuSAzM2JLjfyFPJAeh5rjts: 503

Hint: The Certificate Authority failed to verify the temporary Apache configuration changes made by Certbot. Ensure that the listed domains point to this Apache server and that it is accessible from the internet.

Some challenges have failed.
Ask for help or search for solutions at https://community.letsencrypt.org. See the logfile /var/log/letsencrypt/letsencrypt.log or re-run Certbot with -v for more details.

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!

card icon
Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Sign up
card icon
Hollie's Hub for Good

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

Learn more
card icon
Become a contributor

You get paid; we donate to tech nonprofits.

Learn more
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