Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Let’s Encrypt

How to Secure Nginx on Ubuntu 24.04: A Practical Hardening Guide

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest Ubuntu 24.04 Nginx deployment follows a sequence: patch the host, protect SSH before enabling the firewall, obtain and test a certificate, restrict TLS to current protocols, add response headers, roll out HSTS cautiously, limit abusive requests, and validate every change before reloading Nginx. The commands and configuration below assume a fresh Ubuntu 24.04 LTS server and a site such as example.com; replace example values with your own hostname and SSH port.

What a secure Nginx installation should achieve

Nginx hardening is not one setting. It is a set of controls that reduce different risks:

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • System maintenance: current kernel, OpenSSL, Nginx and dependencies receive security fixes.
  • Administrative access: SSH is reachable only through the intended port and is not accidentally blocked by UFW.
  • Transport security: visitors use a valid certificate and modern TLS rather than clear-text HTTP or obsolete protocols.
  • Information reduction: Nginx does not advertise its exact version in normal responses or error pages.
  • Browser defenses: headers reduce clickjacking, MIME-sniffing and unsafe referrer leakage.
  • Abuse resistance: request-rate limits, fail2ban and useful logs make brute-force and denial-of-service attempts harder to sustain.

No universal percentage describes how much “more secure” a hardened Nginx server is. The result depends on the application, credentials, upstream services, patching discipline and traffic pattern. Treat the controls as layers, not as a guarantee that the application itself is safe.

Confirm the Ubuntu 24.04 support window and patch the host

Ubuntu 24.04 LTS receives standard security maintenance through 31 May 2029. Canonical’s Ubuntu Pro extends coverage to 10 years, and the Legacy add-on extends it to 12 years. Those are operating-system coverage periods; they do not remove the need to update Nginx, your application and any third-party modules.

#1 Best Overall

Apply updates before exposing the service

  1. Connect through your provider’s console or an already working SSH session.
  2. Refresh package metadata and install available updates:
sudo apt update
sudo apt full-upgrade -y
sudo reboot

Reconnect after the reboot and confirm that the expected Ubuntu release is running:

lsb_release -ds
uname -r

Install the core packages in one step:

sudo apt install nginx ufw certbot python3-certbot-nginx fail2ban unattended-upgrades -y

Enable unattended security updates according to your change policy. Automatic updates reduce the time a known vulnerability remains unpatched, but production teams should still monitor reboots, service restarts and application compatibility.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure UFW without locking yourself out

The most damaging firewall mistake is enabling UFW before allowing the SSH path you are currently using. Open the standard SSH service, or your custom TCP port, before enabling the firewall.

Allow SSH first

For the default port:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH

If SSH listens on a custom port, substitute that port instead of using the application profile:

sudo ufw allow 2222/tcp

Do not guess the port. Check the active SSH configuration and your cloud provider’s console settings, then keep one existing session open while testing a second connection.

Open only web traffic, then enable UFW

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

Port 80 is useful for HTTP-to-HTTPS redirects and the HTTP-01 validation method used by many certificate requests. Port 443 carries the encrypted site. If you use a different ACME validation method or do not serve HTTP at all, your firewall rules can be narrower, but do not close a port until you have confirmed how certificate issuance and redirects work for your domain.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recover from an accidental lockout

If a remote session is lost immediately after enabling UFW, use the hosting provider’s out-of-band console. From that console, run sudo ufw allow OpenSSH (or the correct custom-port rule), then verify with sudo ufw status verbose. A console is also the safest way to repair firewall rules when you are changing SSH itself.

Issue a Let’s Encrypt certificate with Certbot

Certbot is an ACME client. With the Nginx plugin it can request a free Let’s Encrypt certificate, install the certificate in the matching server block, and configure an HTTP-to-HTTPS redirect. Your DNS records must already point the hostname to this server, and the validation method must be reachable through the firewall.

Request and install the certificate

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

Follow the prompts for an email address and the terms, and choose the redirect option when Certbot offers it unless your site has a deliberate reason to serve HTTP content. Inspect the resulting server block rather than assuming every application is compatible with a blanket redirect.

Prove renewal works before relying on it

sudo certbot renew --dry-run

A successful dry run exercises the renewal path without replacing the live certificate. Keep the output and investigate failures immediately: common causes include expired DNS records, a blocked port 80, an unexpected proxy, or a server block that no longer matches the certificate name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After a real renewal, reload Nginx only after testing its configuration. If you operate several hostnames, test each one over HTTPS and confirm that the certificate’s names cover every required hostname.

Choose a TLS profile for your actual clients

Disable TLS 1.0 and TLS 1.1. The remaining choice is whether to retain TLS 1.2 for compatibility or require TLS 1.3 only. A profile that is technically stronger but incompatible with a required client is not a usable production profile.

Profile Protocols When to choose it Important considerations
Intermediate TLS 1.2 and TLS 1.3 Public sites with a broad, mixed client population Uses modern ECDHE AES-GCM and ChaCha20 suites; TLS 1.3 suites are selected by OpenSSL. A common starting point also disables session tickets, uses ssl_prefer_server_ciphers off; and supplies a DH parameter file.
Modern TLS 1.3 only Controlled environments where legacy clients are not needed Removes TLS 1.2 compatibility. OCSP stapling and a correctly configured DNS resolver can be added, but test every client first.

Mozilla’s SSL Configuration Generator provides Nginx templates for Modern, Intermediate and Old profiles at https://ssl-config.mozilla.org/. Use its current output as a starting point, then review it against the OpenSSL and Nginx versions installed on Ubuntu 24.04. Do not copy a cipher list from an old tutorial without checking its assumptions.

Example protocol settings

Place the protocol policy in the HTTPS server block or the appropriate shared TLS include:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_session_tickets off;
ssl_dhparam /etc/nginx/dhparam.pem;

The example is an Intermediate starting point. A TLS 1.3-only deployment would use ssl_protocols TLSv1.3; instead, but make that change only after confirming that no required browser, API client, monitoring probe or embedded device depends on TLS 1.2. Generate the referenced parameter file before reloading:

sudo openssl dhparam -out /etc/nginx/dhparam.pem 2048

Keep certificate and private-key permissions restrictive. The private key should be readable by root and by only the processes that genuinely need it.

Consider OCSP stapling for a modern profile

OCSP stapling lets Nginx present a certificate-status response obtained from the certificate authority, reducing some clients’ need to contact the authority themselves. It requires a valid issuer chain and a working DNS resolver. Because resolver and certificate-chain details vary by deployment, enable it only after testing the exact configuration and observing Nginx’s error log.

Hide version details and add security headers

Suppress the Nginx version

In the http block of /etc/nginx/nginx.conf, add:

http {
    server_tokens off;
    # existing configuration ...
}

This removes the Nginx version from generated error pages and the normal Server response field. It does not make the service anonymous: response behavior, TLS fingerprints and application headers can still reveal useful information. Keep Nginx and its modules patched rather than relying on concealment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a reusable header snippet

Create a file that can be included in every public HTTPS server block:

sudo install -d -m 0755 /etc/nginx/snippets
sudo nano /etc/nginx/snippets/security-headers.conf

Example contents:

add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

X-Content-Type-Options: nosniff prevents browsers from treating a response as a different MIME type. X-Frame-Options: SAMEORIGIN permits framing only by the same origin; use DENY when your application never needs to be framed. The referrer policy limits how much URL information is sent to another origin. The always parameter makes the headers appear on error responses as well as successful responses.

Include the snippet inside each relevant server block, not only in a server block that some hostnames never use:

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    include /etc/nginx/snippets/security-headers.conf;
    # certificate, root and application proxy settings ...
}

Header inheritance in Nginx can be surprising when a lower-level block defines its own add_header directives. Inspect the effective configuration with sudo nginx -T and test both normal and error responses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not add obsolete X-XSS-Protection

Modern browsers have dropped the old X-XSS-Protection behavior. Do not add that legacy header as a substitute for a Content Security Policy. CSP can substantially reduce script-injection impact, but it must be designed and tested for each site’s scripts, frames, workers, fonts and third-party services. Begin with a report-only policy where appropriate, then enforce a policy that you have verified against the application.

Roll out HSTS in stages

HTTP Strict Transport Security tells a browser to use HTTPS for a hostname. It is powerful and deliberately difficult to undo, so enable it only after HTTPS, redirects, certificate renewal and every required hostname work reliably.

Start with a short max-age

On the HTTPS server block, begin with a short test value such as 300 seconds:

add_header Strict-Transport-Security "max-age=300" always;

Test the site from a clean browser profile and verify that all assets, redirects, login flows and API endpoints work over HTTPS. Increase the lifetime in measured stages only after you have observed a stable deployment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add subdomains and preload only when ready

includeSubDomains applies the policy to every subdomain. Add it only when every subdomain that users might visit serves valid HTTPS; an overlooked development or mail-related hostname can become unreachable in browsers. The preload token has an even larger operational commitment because browsers can ship the policy before your server is contacted. Use it only when all subdomains are permanently HTTPS and you have reviewed the preload requirements.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Rate-limit abusive requests and ban repeat offenders

Nginx’s limit_req_zone and limit_req can slow brute-force attempts before they consume application resources. Put the shared zone in the http block and apply it only to sensitive locations rather than throttling every static asset.

http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

    server {
        location = /login {
            limit_req zone=login burst=10 nodelay;
            proxy_pass http://app_backend;
        }
    }
}

The rate and burst above are example starting points, not universal limits. Tune them against legitimate login behavior, NAT-heavy networks and your application’s response time. A limit that is too strict becomes a denial of service against real users; a limit that is too loose provides little protection.

Fail2ban can watch Nginx and SSH logs and temporarily ban addresses that repeatedly trigger authentication failures or other configured patterns. Start with the packaged jails, review their filters, and choose ban durations that will not block shared corporate or mobile addresses indefinitely. Rate limiting and fail2ban complement each other: one slows requests at Nginx, while the other reacts to repeated evidence over time.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Monitor the logs that explain failures

Review Nginx’s access and error logs after every major change:

sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/log/nginx/access.log
sudo journalctl -u nginx -f

The error log is especially important after enabling TLS, OCSP stapling, a new include file or an upstream proxy. Look for certificate-chain errors, permission failures, resolver timeouts, upstream connection failures and repeated requests to administrative paths. Feed logs to your normal retention and alerting system so a filled disk or a burst of authentication failures does not go unnoticed.

Validate every change before reloading Nginx

Never reload an untested configuration. The safe change cycle is:

  1. Edit one logical change at a time.
  2. Check syntax and referenced files:
sudo nginx -t
  1. Only after a successful test, reload the service:
sudo systemctl reload nginx
sudo systemctl status nginx --no-pager

A reload normally keeps existing connections while workers adopt the new configuration. If nginx -t fails, do not reload; read the reported file and line, fix the error, and test again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check the externally visible result

From a client outside the server, inspect headers and redirects:

curl -I http://example.com
curl -I https://example.com

Confirm that HTTP reaches the intended HTTPS URL, the certificate name matches, and the response contains X-Content-Type-Options, X-Frame-Options, Referrer-Policy and, when deliberately enabled, HSTS. Verify that the Server field does not expose the Nginx version.

Use https://securityheaders.com/ to review response headers and an SSL/TLS assessment service such as SSL Labs to inspect protocol support, certificate chains and common TLS configuration errors. Treat scanner grades as diagnostics: a score cannot detect insecure application authorization, weak SSH credentials or an unpatched upstream service.

A practical post-hardening checklist

  • System packages are updated and a reboot has been completed when required.
  • SSH (or the custom SSH port) was allowed before UFW was enabled.
  • sudo ufw status verbose shows only the intended inbound ports.
  • DNS points every certificate name to the correct server.
  • Certbot completed and sudo certbot renew --dry-run succeeds.
  • TLS 1.0 and 1.1 are disabled; TLS 1.2 is retained only when the client mix requires it.
  • server_tokens off; is in the http block.
  • Security headers are included in every public server block and use always.
  • HSTS started at a short max-age and has not been expanded to subdomains or preload prematurely.
  • Rate limits are applied to sensitive endpoints and tested with legitimate traffic.
  • Fail2ban, Nginx logs and system journal alerts are being monitored.
  • Every change passed sudo nginx -t before sudo systemctl reload nginx.

Security is an operating routine rather than a one-time edit: keep the host patched, test certificate renewal, review logs, and reassess TLS and header policies whenever your clients or application architecture change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Let’s EncryptLinux securityNGINXserver hardeningTLSUbuntu 24.04UFW

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.