Report this

What is the reason for this report?

How To Secure Nginx with Let's Encrypt on Ubuntu

Updated on November 4, 2025
How To Secure Nginx with Let's Encrypt on Ubuntu

Introduction

Let’s Encrypt is a Certificate Authority (CA) that provides an accessible 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.

In this tutorial, you will use Certbot to obtain a free SSL certificate for Nginx on Ubuntu and set up your certificate to renew automatically.

Key Takeaways

  • Use Certbot’s Nginx plugin to obtain and install free Let’s Encrypt certificates in minutes.
  • Works on Ubuntu 22.04 (Jammy), 24.04 (Noble), and 25.04 (Lunar).
  • Enable auto-renewal; certificates are valid for 90 days and renew automatically.
  • Harden HTTPS with HSTS and modern cipher suites; validate with SSL Labs.
  • Ensure DNS A records and port 80/443 are reachable; most validation failures are networking or DNS-related.

Prerequisites

To follow this tutorial, you will need:

  • One Ubuntu server set up by following this initial server setup for Ubuntu tutorial, including a sudo-enabled non-root user and a firewall.

  • A registered domain name. This tutorial will use example.com throughout. You can purchase a domain name from Namecheap, or use Google Domains or your preferred domain registrar.

  • Both of the following DNS records set up for your server. If you are using DigitalOcean, please see our DNS documentation for details on how to add them.

    • An A record with example.com pointing to your server’s public IP address.
    • An A record with www.example.com pointing to your server’s public IP address.
  • Nginx installed by following How To Install Nginx on Ubuntu. Be sure that you have a server block for your domain. This tutorial will use /etc/nginx/sites-available/example.com as an example.

Step 1 — Installing Certbot

Certbot recommends using their snap package for installation. Snap packages work on nearly all Linux distributions, but they require that you’ve installed snapd first in order to manage snap packages. Ubuntu ships with snap support (22.04, 24.04, 25.04). Start by ensuring snapd is up to date:

  1. sudo snap install core; sudo snap refresh core

If you’re working on a server that previously had an older version of certbot installed, you should remove it before going any further:

  1. sudo apt remove certbot

After that, you can install the certbot package:

  1. sudo snap install --classic certbot

Finally, you can link the certbot command from the snap install directory to your path, so you’ll be able to run it by just typing certbot. This isn’t necessary on all systems, but snaps tend to be less intrusive by default, so they don’t conflict with any other system packages by accident:

  1. sudo ln -s /snap/bin/certbot /usr/bin/certbot

Alternative (APT): On some environments without snapd, you can install from Ubuntu repositories:

  1. sudo apt update
  2. sudo apt install -y certbot python3-certbot-nginx

The snap distribution remains the Certbot team’s recommended installation method for the latest features and timely updates.

Now that we have Certbot installed, let’s run it to get our certificate.

Step 2 — Confirming Nginx’s Configuration

Certbot needs to be able to find the correct server block in your Nginx configuration for it to be able to automatically configure SSL. Specifically, it does this by looking for a server_name directive that matches the domain you request a certificate for.

If you followed the server block set up step in the Nginx installation tutorial, you should have a server block for your domain at /etc/nginx/sites-available/example.com with the server_name directive already set appropriately.

To check, open the configuration file for your domain using nano or your favorite text editor:

  1. sudo nano /etc/nginx/sites-available/example.com

Find the existing server_name line. It should look like this:

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

If it does, exit your editor and move on to the next step.

If it doesn’t, update it to match. Then save the file, quit your editor, and verify the syntax of your configuration edits:

  1. sudo nginx -t

If you get an error, reopen the server block file and check for any typos or missing characters. Once your configuration file’s syntax is correct, reload Nginx to load the new configuration:

  1. sudo systemctl reload nginx

Certbot can now find the correct server block and update it automatically.

Next, let’s 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 for HTTPS traffic. Luckily, Nginx registers a few profiles with ufw upon installation.

You can see the current setting by typing:

  1. sudo ufw status

It will probably look like this, meaning that only HTTP traffic is allowed to the web server:

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

To additionally let in HTTPS traffic, allow the Nginx Full profile and delete the redundant Nginx HTTP profile allowance:

  1. sudo ufw allow 'Nginx Full'
  2. sudo ufw delete allow 'Nginx HTTP'

Your status should now look like this:

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

Next, let’s run Certbot and fetch our certificates.

Step 4 — Obtaining an SSL Certificate

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

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

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

When running the command, you will be prompted to enter an email address and agree to the terms of service. After doing so, you should see a message telling you the process was successful and where your certificates are stored:

Output
IMPORTANT NOTES: 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-06-01. These files will be updated when the certificate renews. Certbot has set up a scheduled task to automatically renew this certificate in the background. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 downloaded, installed, and loaded, and your Nginx configuration will now automatically redirect all web requests to https://. Try reloading your website and notice your browser’s security indicator. It should indicate that the site is properly secured, usually with a lock icon. If you test your server using the SSL Labs Server Test, it will get an A grade.

Let’s finish by testing the renewal process.

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. The certbot package we installed takes care of this for us by adding a systemd timer that will run twice a day and automatically renew any certificate that’s within thirty days of expiration.

You can query the status of the timer with systemctl:

  1. sudo systemctl status snap.certbot.renew.service
Output
○ snap.certbot.renew.service - Service for snap application certbot.renew Loaded: loaded (/etc/systemd/system/snap.certbot.renew.service; static) Active: inactive (dead) TriggeredBy: ● snap.certbot.renew.timer

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.

If you prefer hooks, you can add a post-hook to reload Nginx only when a certificate is renewed:

  1. sudo certbot renew --dry-run --post-hook "systemctl reload nginx"

On systems using APT packages, a cron job may handle renewals; with snap, a systemd timer (snap.certbot.renew.timer) runs twice daily.

Configuring HTTPS Best Practices (HSTS, Ciphers, Redirects)

Strengthen your TLS configuration to reduce downgrade and mixed-content risks.

  • Enable HSTS to force HTTPS in supported browsers:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
  • Prefer modern TLS protocols and ciphers (adjust to your risk profile):
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
  • Redirect HTTP to HTTPS (Certbot can add this automatically):
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}
  • Validate your config with industry tools:
    • Mozilla SSL Configuration Generator (https://ssl-config.mozilla.org)
    • SSL Labs Server Test (https://www.ssllabs.com/ssltest/)

Note: Be cautious with HSTS on first enablement. If you set preload, submit your domain only after confirming a stable HTTPS setup for all subdomains.

Practice Why it’s important? How to apply
Use 301 from HTTP to HTTPS Users land on the secure URL quickly Certbot auto-writes redirects, or add a port 80 server returning 301 https://$host$request_uri
Minimize redirect hops Fewer round trips = faster first paint Point DNS/canonical links to final HTTPS host; avoid http → www → https chains
Serve all assets over HTTPS Prevents mixed‑content warnings and broken UI Audit with DevTools Security panel; update CDNs/asset URLs to https://
Enable HTTP/2 and HTTP/3 Faster multiplexed delivery, better mobile performance In Nginx, listen 443 ssl http2; and, if supported, http3/QUIC on 443/udp
Enable TLS session resumption Quicker repeat visits Ensure ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d;
Turn on OCSP stapling Faster and more reliable cert validation ssl_stapling on; ssl_stapling_verify on; with valid resolver
Prefer Brotli/Gzip Smaller payloads for HTML/CSS/JS Enable brotli on; (if module present) and gzip on; as fallback
Set clear canonical HTTPS URLs Avoid duplicate content and confusing URLs Use <link rel="canonical" href="https://example.com/..."> and update sitemaps
Consolidate www vs apex Predictable addressing and fewer redirects Pick one hostname; redirect the other permanently to it
Friendly TLS error/maintenance pages Reduce abandonment during incidents Custom error_page 497/403/502/503 with clear next steps
Monitor renewals and failures Prevent sudden cert expiry lockouts Alert on certbot logs; external checks; email deliverability verified
Phase in HSTS cautiously Avoid accidental lock‑in during rollout Start without preload; add subdomains gradually; verify before submitting preload

Common Issues and Fixes

  • ACME HTTP-01 challenge fails: Ensure port 80 is reachable from the internet and not blocked by a firewall or upstream load balancer.
  • DNS mismatch: Confirm A/AAAA records for example.com and www.example.com point to the correct public IP.
  • Wrong Nginx server_name: Certbot locates the server block by server_name; verify it matches the requested domains.
  • Rate limits: Repeated failed requests can hit Let’s Encrypt rate limits. Use --dry-run during testing and vary subdomains if needed.
  • Snap vs APT conflicts: Remove older APT certbot before installing snap to avoid path conflicts.

FAQs

1. What is Let’s Encrypt and how does it work with Nginx?

Let’s Encrypt is a free CA that verifies domain control and issues SSL/TLS certificates via the ACME protocol. Certbot automates domain validation (HTTP‑01 for most cases, DNS‑01 for wildcard), certificate issuance, Nginx configuration, and renewals. With the Nginx plugin, Certbot updates your server block and writes certificate files to /etc/letsencrypt/live/your_domain/.

2. Do I need a domain name to use Let’s Encrypt SSL?

Yes. Publicly trusted certificates require a registered domain with public DNS pointing to your server—IP‑only or private hostnames are not supported. Use A/AAAA records for each hostname you request. Wildcard certificates (e.g., *.example.com) require DNS‑01 validation and access to edit DNS.

3. How do I install Certbot on Ubuntu for Nginx?

Use snap (recommended): sudo snap install --classic certbot && sudo ln -s /snap/bin/certbot /usr/bin/certbot. Alternatively, sudo apt install certbot python3-certbot-nginx.

The snap package receives updates fastest and includes the Nginx plugin. Verify the version with certbot --version. If snap is unavailable, APT works but can lag in features; ensure python3-certbot-nginx is installed so Certbot can edit Nginx automatically.

4. Can I secure multiple domains or subdomains with one certificate?

Yes, Let’s Encrypt allows you to secure multiple domains and subdomains using a single certificate, known as a SAN (Subject Alternative Name) certificate. Instead of requesting and managing separate certificates for each hostname, you can combine them all under one certificate—making management and renewal much simpler.

How to do it:
When running Certbot, you can specify each domain or subdomain you want to include on your certificate by repeating the -d flag for each one. For example:

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

This command will obtain one certificate that is valid for all three names (example.com, www.example.com, api.example.com). Certbot will automatically update your Nginx configuration to use the new certificate for all listed domains.

What about wildcard domains?
If you want a certificate that covers all subdomains (such as anything.example.com), you can use a wildcard domain. This requires DNS-01 validation (proving you have control over your DNS zone), usually by adding a special TXT record to your DNS provider. For example:

sudo certbot --manual --preferred-challenges dns -d *.example.com -d example.com

You’ll be prompted to create specific DNS records during this process.

Other things to know:

  • You must ensure that all specified domains are correctly pointed to your server before running Certbot.
  • Be aware of Let’s Encrypt rate limits: try to group related domains into as few certificates as necessary, to minimize the chance of hitting these limits.
  • When renewing, Certbot will keep all the original domains together unless you request a new set.

Using multiple -d options with Certbot is the recommended way to cover several domains/subdomains. Certificates with many SANs are ideal for sites and APIs on the same project or server.

5. How do I confirm auto-renewal is working?

Run sudo systemctl status snap.certbot.renew.timer (snap) and sudo certbot renew --dry-run. Check logs in /var/log/letsencrypt/. You can also verify expiry:

  1. openssl x509 -in /etc/letsencrypt/live/your_domain/fullchain.pem -noout -enddate

On success, renewals occur automatically when a cert is within 30 days of expiry and Nginx is reloaded.

6. How do I configure Nginx to use the Let’s Encrypt certificate?

Certbot automatically configures Nginx with the Let’s Encrypt certificate. Typical directives in your TLS server block are:

ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem;

Validate with sudo nginx -t and apply with sudo systemctl reload nginx.

7. How can I test if my HTTPS configuration is correct?

Use external tests and client checks:

  • SSL Labs Server Test: https://www.ssllabs.com/ssltest/
  • Mozilla SSL Config Generator guidance: https://ssl-config.mozilla.org
  • Quick checks:
  1. curl -I http://example.com # Expect 301 to https
  2. curl -I https://example.com # Confirm 200 and HSTS if enabled
  3. openssl s_client -connect example.com:443 -servername example.com -tls1_3 < /dev/null | openssl x509 -noout -dates -issuer -subject

Also open DevTools → Security to spot mixed‑content warnings.

8. How do I set up automatic renewal for Let’s Encrypt certificates?

With snap installs, a systemd timer (snap.certbot.renew.timer) runs twice per day and renews certificates nearing expiry. Verify with systemctl status and simulate with sudo certbot renew --dry-run. If you need hooks, use:

  1. sudo certbot renew --post-hook "systemctl reload nginx"

Ensure port 80/443 are reachable, DNS is correct, and the notification email is monitored so renewal issues are caught early.

Conclusion

In this tutorial, you installed the Let’s Encrypt client certbot, downloaded SSL certificates for your domain, configured Nginx to use these certificates, and set up automatic certificate renewal. You also hardened your TLS configuration with HSTS and modern ciphers and reviewed common troubleshooting steps. If you have further questions about using Certbot, the official documentation is a good place to start.

Looking ahead: For teams managing many domains, consider infrastructure-as-code automation (e.g., Ansible roles for Nginx + Certbot), DNS-01 challenges for wildcard certificates, and proactive certificate monitoring with alerting—areas well-suited for a separate advanced guide.

Further Reading

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

Learn more about our products

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 author(s)

Alex Garnett
Alex Garnett
Author
Senior DevOps Technical Writer
See author profile

Former Senior DevOps Technical Writer at DigitalOcean. Expertise in topics including Ubuntu 22.04, Linux, Rocky Linux, Debian 11, and more.

Anish Singh Walia
Anish Singh Walia
Author
Sr Technical Writer
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Still looking for an answer?

Was this helpful?


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!

I got a error when doing the Cert generation:

"Certbot failed to authenticate some domains (authenticator: nginx). the Certificate Authority reported these problems:

Domain: <mydomain> Type: dns Detail: no valid A records found for <mydomain>"

Domain is reachable from web-browser and DigitalOcean DNS settings all look correct. HTTP-01 challenge is failing. Is this a UFW settings issue (my UFW firewall setting match the tutorial).

And now I’m stuck with too many failed authorizations problem as well.

Any thoughts…

Worked like a charm! thank you

As soon as there is a second domain block, this does not work anymore. The error “ipv6conf may only be defined once” occurs. Any chance you could address this problem in your article, too? Maybe even with a solution?

This comment has been deleted

When You Setup Full Process Correctly But You See Your Static File Not Serving Properly.That’s Mean Your Website not Showing CSS Or Your website Style Correctly.

[solved]

  • Sometimes Nginx Not Serving Static File Correctly, They are Just Permission Denied.
  • To See Log & Get Your Error.
sudo tail -30 /var/log/nginx/error.log
  • You should give the user that runs the Nginx process permissions to read the file.
sudo usermod -a -G your-user www-data

Next Test & Restart Your Nginx Server.

sudo nginx -t
sudo systemctl restart nginx

Note: That Happen When You Add New User Rather Than root. But Not Give Every Permission

To Get That Type Content Visit: chapterclose.com

I’m viewing the page for Ubuntu 22.04 but it’s showing commands for nginx…

In the following GitHub Gist, there has instructions to install certbot in another way (I also had issue installing certbot directly) and making the ssl certificate. The whole gist contains, A to Z of server setup (including the background job setup, scheduler, etc). Please don’t hesitate to reply to this mail or comment on the gist if you face any trouble. I would love to assist you. Thanks.

https://gist.github.com/FaridLU/377f6adf3cdfd748d430f42e393417f7#deployment-part-iv-domain-setup--ssl-certificate-lets-encrypt

This content is invaluable. I don’t regularly make changes to the sites I deploy, but when I need to your documentation is always bang on the money. Thank you so much. You save a lot of hair-pulling :-)

Here is a handy command to output your expiration date for the SSL certificate:

echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -dates

OUTPUT:

notBefore=Jun 26 01:18:45 2024 GMT
notAfter=Sep 24 01:18:44 2024 GMT

Ubuntu should already have the openssl command available.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

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.