Securing Nginx with SSL/TLS (HTTPS)
8 min read
Welcome! So you've got your Nginx server up and running, dishing out web pages like a champ. But there's a problem. Right now, your server is talking to your users in plain text. It's like shouting conversations across a crowded room—anyone can listen in. Not great for privacy or security.
The Problem: Unencrypted HTTP traffic is vulnerable. It can be intercepted, read, and even modified by attackers. Modern browsers rightfully flag these sites as "Not Secure," which can scare away users and hurt your search engine rankings.
The Solution: We need to wrap our traffic in a secure, encrypted layer. This is where SSL/TLS comes in, upgrading our web address from http:// to the much more trustworthy https://. This guide will walk you through setting this up, making your corner of the internet a safer place.
1. The Basics of SSL/TLS and Obtaining Certificates (Let's Encrypt) 📜
Before we can secure our server, we need to understand the tools for the job: SSL/TLS and SSL certificates.
What are SSL/TLS?
SSL (Secure Sockets Layer) and its modern successor, TLS (Transport Layer Security), are cryptographic protocols that provide secure communication over a computer network. Think of it as a secret handshake between a user's browser and your server that establishes a private, encrypted channel for all their communication. We'll mostly be using TLS, as older SSL versions are now considered insecure.
What is an SSL Certificate?
An SSL certificate is a digital "passport" or ID card for your website. It does two critical things:
- Authenticates Identity: It proves to visitors that your website is genuinely who it claims to be.
- Enables Encryption: It contains the public key needed to initiate the secure, encrypted connection.
These certificates are issued by trusted third parties called Certificate Authorities (CAs).
The Old Problem: Getting a certificate used to be a manual, often expensive, process. You'd have to prove your identity and pay a yearly fee to a CA.
The Modern Solution: Let's Encrypt
Let's Encrypt is a free, automated, and open Certificate Authority that has revolutionized web security. It provides free SSL/TLS certificates in a completely automated way. The tool most commonly used to interact with Let's Encrypt is Certbot.
Getting Started with Certbot on Ubuntu
Let's get our hands dirty and install Certbot. The recommended way to install Certbot is using snap because it ensures you have the latest version with all security updates.
Step 1: Install Certbot
First, if you have any old versions of Certbot installed via apt, it's a good idea to remove them to avoid conflicts.
sudo apt-get remove certbotNow, install Certbot using snap.
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbotStep 2: Obtain Your First Certificate
Certbot's Nginx plugin makes this incredibly easy. It will automatically detect the domain names from your Nginx configuration, obtain a certificate, and even configure Nginx for you.
Make sure your Nginx configuration file for your site (e.g., /etc/nginx/sites-available/yourdomain.com) has a server_name directive set correctly.
server {
server_name yourdomain.com www.yourdomain.com;
# ... other configurations
}Now, run Certbot with the Nginx plugin.
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.comCertbot will guide you through a few questions, including entering your email for renewal notices and agreeing to the terms of service. It will then communicate with Let's Encrypt to verify you own the domain and fetch your certificate. The certificate and private key files will typically be stored in /etc/letsencrypt/live/yourdomain.com/.
Let's Encrypt certificates are valid for 90 days, but don't worry! The Certbot package automatically creates a systemd timer or cron job that renews your certificates before they expire. You can test the renewal process with a dry run:
sudo certbot renew --dry-run2. Configuring Server Blocks for Port 443 (HTTPS) ⚙️
When you ran sudo certbot --nginx, it did its best to automatically edit your Nginx configuration. Let's look at what it did and understand the key pieces.
HTTP traffic uses port 80, while encrypted HTTPS traffic uses port 443. We need a server block that listens on port 443 and knows where to find our new SSL certificate and private key.
Here is a minimal example of what your HTTPS server block should look like:
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
# SSL Certificate and Key files
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
# Include other SSL parameters (we'll cover this later)
# include /etc/letsencrypt/options-ssl-nginx.conf;
root /var/www/yourdomain.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Breaking Down the Directives:
listen 443 ssl;: This tells Nginx to listen for incoming connections on port 443 and to handle them using the SSL/TLS protocol. In older versions, you might have seenssl on;, but this directive is now deprecated.ssl_certificate: This directive points to your public certificate file (fullchain.pem). This file contains your server's certificate plus any intermediate certificates needed to build a chain of trust back to the Certificate Authority.ssl_certificate_key: This points to your private key file (privkey.pem). This key is secret and must be protected. It's the counterpart to your public certificate and proves your server is the legitimate owner.
After making any changes to your configuration files, always test the configuration syntax before reloading Nginx:
sudo nginx -t
sudo systemctl reload nginx3. Enforcing Security: Forcing HTTP to HTTPS Redirects ↪️
Just because your site is available over HTTPS doesn't mean users will use it. If someone types yourdomain.com into their browser, it will default to HTTP on port 80. We need to close this insecure door and force everyone to use the secure HTTPS entrance.
The Problem: Leaving port 80 open without a redirect allows for unencrypted connections, defeating the purpose of setting up SSL and creating security risks.
The Solution: We will create a separate server block that listens on port 80 for the sole purpose of redirecting all traffic to the HTTPS version of the site. The industry standard is to use a 301 Moved Permanently redirect. This tells browsers and search engines that the HTTPS version is the official one.
Here is the standard, most efficient way to configure this redirect:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}Breaking It Down:
listen 80;: Listens for all insecure HTTP traffic.server_name yourdomain.com www.yourdomain.com;: Catches requests for your specific domains. You could also useserver_name _;to catch all hostnames.return 301 https://$host$request_uri;: This is the magic.return 301: Immediately stops processing and sends a 301 "Moved Permanently" response code.https://$host$request_uri: Constructs the new URL.$hostis the domain the user requested (e.g.,yourdomain.com), and$request_uriis the full path and query string (e.g.,/about/team?member=jane). This ensures that a link tohttp://yourdomain.com/pricingcorrectly redirects tohttps://yourdomain.com/pricing.
After adding this block to your configuration, test and reload Nginx. Now, any attempt to access your site via HTTP will be instantly and permanently redirected to the secure HTTPS version.
4. SSL Optimization: Session Caching, Protocols, and Secure Ciphers 🚀
Having a basic HTTPS setup is great, but for a production environment, we can make it faster and even more secure. The initial SSL/TLS handshake can be resource-intensive, and using outdated protocols or weak encryption ciphers can expose you to vulnerabilities.
SSL Session Caching
- Problem: Every new connection requires a full cryptographic handshake, which adds latency.
- Solution: Enable a shared SSL session cache. This allows returning clients to resume a previous session, skipping the full handshake and speeding up subsequent connections.
# Add this inside your http block in nginx.conf
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;ssl_session_cache shared:SSL:10m;: Creates a shared cache named "SSL" that is 10 megabytes in size (enough for about 40,000 sessions). It's shared across all Nginx worker processes.ssl_session_timeout 10m;: Tells clients they can reuse a session for up to 10 minutes.
Secure Protocols
- Problem: Older protocols like SSLv3, TLS 1.0, and TLS 1.1 have known vulnerabilities.
- Solution: Explicitly configure Nginx to only use modern, secure protocols like TLS 1.2 and TLS 1.3.
# Add this inside your server block for port 443
ssl_protocols TLSv1.2 TLSv1.3;Fact: TLS 1.3 is not only more secure but also faster because it streamlines the handshake process, reducing the number of round-trips required to establish a connection.
Secure Ciphers
- Problem: A cipher suite is the specific set of algorithms used for encryption. Some older ciphers are now considered weak and can be broken.
- Solution: Provide a list of strong, modern cipher suites and tell the server to choose the best one, not the client.
Instead of manually maintaining a long, complex string of ciphers, it's highly recommended to use a trusted, up-to-date configuration from a reputable source like Mozilla.
You can use the Mozilla SSL Configuration Generator to get a modern, secure configuration tailored to your Nginx version.
A modern cipher configuration might look like this:
# Add these inside your server block for port 443
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';ssl_prefer_server_ciphers on;: Ensures that your server's cipher preference is used, not the client's.
By implementing these optimizations, you not only harden your server against attacks but also improve performance for your users.
References for Extra Reading 📚
- Nginx SSL/TLS Module Documentation: nginx.org/en/docs/http/ngx_http_ssl_module.html
- Let's Encrypt: letsencrypt.org
- Certbot Instructions: certbot.eff.org
- Mozilla SSL Configuration Generator: ssl-config.mozilla.org
Challenge
You are tasked with securing an Nginx server for the domain yourdomain.com. Starting with the provided basic HTTP configuration, you must implement a full SSL/TLS setup.
Your Tasks:
- Create an HTTPS Server Block: Add a new
serverblock that listens on port 443 for secure SSL/TLS traffic. - Configure SSL Certificates: Point the new server block to the Let's Encrypt certificate files. The full chain is at
/etc/letsencrypt/live/yourdomain.com/fullchain.pemand the private key is at/etc/letsencrypt/live/yourdomain.com/privkey.pem. - Enforce Redirection: Modify the original
serverblock (listening on port 80) to issue a permanent redirect (301) for all incoming HTTP requests to their corresponding HTTPS URLs. - Harden Security & Performance: Within the HTTPS server block, implement the following optimizations:
- Restrict the server to use only
TLSv1.2andTLSv1.3protocols. - Enable a shared SSL session cache named
SSLwith a size of10mand a timeout of10m. - Prioritize the server's cipher suites over the client's.
- Set the
ssl_ciphersto the following strong suite:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384.
- Restrict the server to use only
Expected result
The final configuration should consist of two server blocks.
HTTP Block (Port 80): This block should be minimal, containing only the
listen,server_name, and areturn 301 https://$host$request_uri;directive to enforce the HTTPS redirect.HTTPS Block (Port 443): This block should:
- Listen on port 443 with the
sslparameter (listen 443 ssl;). - Specify the correct
server_name. - Include the
ssl_certificateandssl_certificate_keydirectives pointing to the correct file paths. - Contain the security and performance directives:
ssl_protocols,ssl_ciphers,ssl_prefer_server_ciphers,ssl_session_cache, andssl_session_timeoutwith their specified values. - Retain the original
root,index, andlocationblock configuration for serving content.
- Listen on port 443 with the