Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

Securing Nginx with SSL/TLS on Ubuntu: Advanced Tips and Tricks

Published

nginxFirewall and Security

SSL and TLS certificates keep websites safe by hiding data between browsers and servers. When people visit your website with HTTPS, their personal information stays protected. Ubuntu servers running Nginx need SSL certificates for safety and better search results.

Browsers show warnings for websites without HTTPS. They mark HTTP sites as not secure which makes your website look bad. Google puts HTTPS sites higher in search results so SSL certificates help people find your website.

Without SSL certificates, passwords and credit card numbers travel across the internet without protection. Anyone watching network traffic can see this information. Even simple websites need SSL because visitors trust secure sites more.

SSL certificates used to cost money and were hard to install. Now they are free and easy to set up. Lets Encrypt gives certificates at no cost and updates them automatically every three months. This removes the problems that stopped website owners from using HTTPS before.

This guide shows everything needed to make your Nginx web server secure on Ubuntu. You will learn how to get certificates, install them right, and keep security working over time. We focus on steps that work for real websites.

Understanding SSL and TLS Certificates

SSL means Secure Sockets Layer and TLS means Transport Layer Security. TLS replaced SSL years ago but people still say both names. Websites today use TLS version 1.2 or 1.3 for the best safety.

Different types of certificates check different things. Domain Validated certificates only check that you own the website name. These work fine for most websites and blogs. Organization Validated certificates also check your business information. Extended Validation certificates check the most and show your company name in the browser address bar.

Certificates also work differently for how many websites they cover. Single domain certificates work for one website address. Wildcard certificates cover your main website plus all subdomains using a star symbol. Multi-domain certificates can protect several different website addresses with one certificate.

Free certificates from Lets Encrypt work just like expensive ones. They use the same protection strength and all browsers trust them. The main difference is that free certificates last only 90 days instead of one to three years. Automatic updates solve this problem completely.

Certificate Authorities are companies that make and check SSL certificates. They verify that you actually control the website before giving certificates. Big browsers keep lists of trusted Certificate Authorities. Certificates from these trusted sources work automatically in all browsers.

Popular Certificate Authorities include Lets Encrypt for free certificates plus paid options like DigiCert, Sectigo, and GlobalSign. Lets Encrypt has made over one billion certificates and powers HTTPS for millions of websites around the world.

Preparing Ubuntu Server

Your Ubuntu server needs setup before installing SSL certificates. Start by updating all software to get the latest security fixes and make sure certificate tools work right.

Update your system with these commands:

sudo apt update
sudo apt upgrade -y

Install snap package manager parts needed for Certbot:

sudo apt install snapd
sudo snap install core
sudo snap refresh core

Set up the firewall to allow web traffic on both HTTP and HTTPS ports. Ubuntu has UFW firewall which makes this easy:

sudo ufw allow OpenSSH
sudo ufw allow Nginx Full
sudo ufw enable

The Nginx Full setting opens ports 80 and 443 for HTTP and HTTPS traffic. Keeping SSH access stops you from getting locked out of your server during setup.

Check that Nginx web server is installed and working:

sudo systemctl status nginx

Install Nginx if it is not there already:

sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

Test your web server by opening your server IP address in a browser. You should see the default Nginx welcome page. This shows the web server responds to requests properly.

Your website name must point to your server IP address before getting certificates. Update DNS records with your domain company if needed. Use these commands to check DNS settings:

nslookup yourdomain.com
dig yourdomain.com

Both should show your server IP address. DNS changes can take up to 48 hours to work across the internet.

Make a basic website folder and test page:

sudo mkdir -p /var/www/yourdomain.com/html
sudo chown -R www-data:www-data /var/www/yourdomain.com/html
echo "Hello World" | sudo tee /var/www/yourdomain.com/html/index.html

Getting SSL Certificates with Lets Encrypt

Lets Encrypt gives free SSL certificates through an automated system called ACME. Certbot is the official tool for getting and managing these certificates. It handles everything automatically.

Install Certbot using the snap package manager:

sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

Making a link lets you run Certbot from anywhere on your system.

Check your website name points to your server before asking for certificates. Lets Encrypt tests that you control the website by accessing it over the internet:

ping yourdomain.com

The answer should show your server IP address.

Get certificates for your website using the Nginx plugin:

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

Certbot will ask for your email address to send renewal reminders. You must also agree to the terms of service. The tool automatically checks website ownership and sets up Nginx.

The checking process makes temporary files on your web server. Lets Encrypt accesses these files to confirm you control the website. This happens automatically and takes only a few minutes.

For wildcard certificates that cover all subdomains, use DNS checking:

sudo certbot certonly --manual --preferred-challenges=dns -d *.yourdomain.com

This way needs adding a special DNS record. Certbot shows the exact record to make in your DNS settings. Wildcard certificates work well when you have many subdomains.

Get certificates without automatic Nginx setup:

sudo certbot certonly --nginx -d yourdomain.com

This way gives you more control over the web server setup but needs manual setup afterward.

Certificates are kept in /etc/letsencrypt/live/yourdomain.com/ with these important files:

  • fullchain.pem – has your certificate plus middle certificates
  • privkey.pem – has your private key
  • cert.pem – has only your certificate
  • chain.pem – has middle certificates

Setting Up Nginx for SSL

Certbot automatically updates Nginx setup when using the –nginx option. Understanding this setup helps with changes and fixing problems. Manual installation also needs editing these files.

A complete SSL server block looks like this:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;
    
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    
    root /var/www/yourdomain.com/html;
    index index.html index.htm index.php;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

The setup turns on SSL on port 443 with HTTP/2 support. The ssl_certificate line points to your certificate file and ssl_certificate_key points to your private key.

Redirect all HTTP traffic to HTTPS with a separate server block:

server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$server_name$request_uri;
}

This makes all visitors use the secure HTTPS version of your site. The 301 status code tells search engines this is a permanent redirect.

Test your setup before applying changes:

sudo nginx -t

If the test passes without errors, reload Nginx:

sudo systemctl reload nginx

Visit your website to make sure HTTPS works properly. You should see a lock icon in the browser address bar showing a secure connection.

Advanced SSL Security Settings

Basic SSL installation gives encryption but extra settings make security better. These setups protect against different attacks and get higher security ratings.

Turn on HTTP/2 protocol for better performance:

listen 443 ssl http2;
listen [::]:443 ssl http2;

HTTP/2 loads web pages faster through multiplexing and header compression. Most modern browsers support this protocol.

Set up strong encryption protocols and ciphers:

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;

This turns off older weak protocols while turning on the most secure options. Modern browsers pick the best available cipher automatically.

Add HTTP Strict Transport Security to stop downgrade attacks:

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

HSTS tells browsers to always use HTTPS for your website even if users type HTTP addresses. This stops many common attacks.

Turn on OCSP stapling for faster certificate checking:

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

OCSP stapling lets your server check certificate status and include it in SSL handshakes. This reduces connection time for visitors.

Set up SSL session caching to make performance better:

ssl_session_cache shared:le_nginx_SSL:10m;
ssl_session_timeout 1440m;
ssl_session_tickets off;

Session caching lets returning visitors connect faster by reusing SSL session information.

Add security headers to protect against common web attacks:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;

These headers stop clickjacking, cross-site scripting, and other security problems.

Testing SSL Setup

Complete testing makes sure your SSL setup works correctly and securely. Use both online tools and command line tools to check everything works properly.

SSL Labs gives free online testing at ssllabs.com/ssltest. Enter your website name to get a detailed security report with grades from A+ to F. This tool checks for common problems and setup issues.

Test SSL locally using OpenSSL:

openssl s_client -connect yourdomain.com:443 -servername yourdomain.com

This command shows detailed connection information including supported protocols and chosen cipher. Look for TLS version and certificate chain information.

Check certificate end dates:

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

This shows when your certificate ends. Lets Encrypt certificates last 90 days from issue date.

Check HTTP to HTTPS redirect:

curl -I http://yourdomain.com

You should see a 301 redirect response pointing to the HTTPS version.

Test your website in different browsers including Chrome, Firefox, Safari, and Edge. Check that the secure lock icon appears and no mixed content warnings show up.

Use browser developer tools to find mixed content issues. Press F12 and look for resources loaded over HTTP on HTTPS pages. Update these to use HTTPS or relative URLs.

Check certificate chain completeness:

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

This shows detailed certificate information including who issued it and subject details.

Certificate Management and Renewal

Lets Encrypt certificates end every 90 days and need regular renewal. Certbot automatically sets up renewal using systemd timers on Ubuntu systems. This happens without any manual work.

Test renewal without actually renewing certificates:

sudo certbot renew --dry-run

This pretends to do the renewal process and catches problems before they affect live certificates. Run this test monthly to make sure everything works properly.

View all installed certificates and end dates:

sudo certbot certificates

This lists every certificate managed by Certbot with websites covered and end information.

Check automatic renewal timer status:

sudo systemctl status snap.certbot.renew.timer
sudo systemctl list-timers snap.certbot.renew.timer

The timer runs twice daily and renews certificates ending within 30 days. View renewal activity logs:

sudo journalctl -u snap.certbot.renew.service

Manually renew specific certificates when needed:

sudo certbot renew --cert-name yourdomain.com

Force early renewal for testing purposes:

sudo certbot renew --force-renewal

Make monitoring scripts to check certificate end dates:

#!/bin/bash
DOMAIN="yourdomain.com"
EXPIRE_DATE=$(echo | openssl s_client -servername $DOMAIN -connect $DOMAIN:443 2>/dev/null | openssl x509 -noout -dates | grep notAfter | cut -d= -f2)
EXPIRE_SECONDS=$(date -d "$EXPIRE_DATE" +%s)
NOW_SECONDS=$(date +%s)
DAYS_LEFT=$(( (EXPIRE_SECONDS - NOW_SECONDS) / 86400 ))

if [ $DAYS_LEFT -lt 7 ]; then
    echo "WARNING: Certificate ends in $DAYS_LEFT days"
fi

Save this as a script and run it regularly through cron jobs to get early warning of renewal problems.

Security Best Practices

Keeping strong security needs ongoing attention to setup and updates. Follow these practices to keep your SSL setup secure over time.

Keep your system updated with regular security patches:

sudo apt update && sudo apt upgrade
sudo snap refresh

Updates fix security problems and make compatibility better with new certificate features.

Use strong server login methods. Turn off password login for SSH access:

sudo nano /etc/ssh/sshd_config

Set PasswordAuthentication to no and use SSH keys instead. This stops brute force attacks on your server.

Watch certificate files permissions:

sudo ls -la /etc/letsencrypt/live/yourdomain.com/

Certificate files should only be readable by root and web server users. Wrong permissions can expose private keys.

Backup certificates and private keys to secure places. While Lets Encrypt certificates renew automatically, backups stop service interruption during problems:

sudo tar -czf ssl-backup-$(date +%Y%m%d).tar.gz /etc/letsencrypt/

Store backups on separate systems or cloud storage with strong encryption.

Check server logs regularly for suspicious activity:

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

Look for unusual traffic patterns, failed login attempts, or error messages.

Use fail2ban to block repeated attack attempts:

sudo apt install fail2ban

Set it up to watch Nginx logs and block IP addresses making too many failed requests.

Use Content Security Policy headers to stop code injection attacks:

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'" always;

Adjust the policy based on your website specific needs while keeping security.

Common Issues and Solutions

SSL setup can have different problems. Understanding common issues and their solutions stops long downtime and security problems.

Certificate Chain Problems

Certificate chain problems cause browser warnings even with valid certificates. Always use fullchain.pem instead of cert.pem in your Nginx setup. The full chain includes middle certificates needed by browsers.

Mixed Content Warnings

Mixed content warnings appear when HTTPS pages load HTTP resources. Update image sources, stylesheets, and scripts to use HTTPS:

<img src="https://example.com/image.jpg" alt="Example">
<link rel="stylesheet" href="https://example.com/style.css">
<script src="https://example.com/script.js"></script>

Use relative URLs when possible to avoid protocol issues:

<img src="/images/photo.jpg" alt="Photo">

Automatic Renewal Failures

Automatic renewal failures have several common causes. Check Certbot logs for specific error messages:

sudo journalctl -u snap.certbot.renew.service

Firewall blocking stops Lets Encrypt from accessing verification files. Make sure ports 80 and 443 are open:

sudo ufw status
sudo ufw allow Nginx Full

DNS problems happen when website names do not point to your server. Check DNS settings:

nslookup yourdomain.com
dig yourdomain.com

File permission errors stop Certbot from making verification files:

sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

Rate Limiting Issues

Rate limiting happens when asking for too many certificates in short periods. Lets Encrypt limits certificate requests per website and IP address. Use staging environment for testing:

sudo certbot --staging --nginx -d yourdomain.com

Configuration Errors

Nginx setup errors stop SSL from working properly. Test setup syntax:

sudo nginx -t

Fix any errors before reloading Nginx. Common problems include missing semicolons, wrong file paths, and syntax mistakes.

Performance Issues

Performance issues with SSL can slow down your website. Turn on gzip compression:

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

Make SSL settings better for performance:

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

Conclusion

SSL certificates are now needed for every website no matter the size or purpose. Lets Encrypt makes HTTPS available to everyone through free certificates and automated management. Proper setup protects your visitors and makes search engine rankings better.

The automated renewal system removes the maintenance work that stopped SSL adoption before. Once set up correctly, certificates renew themselves without interruption to your website service.

Regular watching makes sure continued security and catches problems before they affect visitors. Simple scripts can check certificate end dates and renewal status automatically.

Following the security practices in this guide makes a strong foundation for web security. SSL certificates are just one part of overall security but they form a critical foundation that enables other protections.

Stay informed about security developments and update your setups as needed. The web security landscape changes constantly but SSL and TLS remain fundamental to online safety.

Remember that security is an ongoing process rather than a one-time setup. Regular maintenance, watching and updates make sure your website remains secure and trustworthy for all visitors.

Related guides

Account services are unavailable until the production backend is configured.