Nginx Config by Example: SSL/TLS
Securing connections with HTTPS through this sample code demonstrating SSL certificate configuration, protocol and cipher selection for security, session caching for performance, HTTP/2 enablement, and HTTP to HTTPS redirection.
Code
server {
listen 443 ssl http2;
server_name example.com;
# Certificate paths
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Modern security settings
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# Session caching
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location / {
root /var/www/html;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}Explanation
SSL/TLS configuration in Nginx enables HTTPS by listening on port 443 with the ssl parameter and specifying paths to the SSL certificate (public key) and certificate key (private key). The http2 parameter enables HTTP/2 protocol support, which provides performance improvements through multiplexing, header compression, and server push capabilities. Certificates can be obtained from Certificate Authorities like Let's Encrypt, which provides free automated certificates.
Security configuration requires explicitly defining allowed protocols and cipher suites. The ssl_protocols directive should disable outdated protocols like SSLv3, TLSv1.0, and TLSv1.1, supporting only TLSv1.2 and TLSv1.3 for modern security. The ssl_ciphers directive specifies allowed encryption algorithms, with HIGH selecting strong ciphers and !aNULL:!MD5 excluding weak ones. The ssl_prefer_server_ciphers on directive ensures the server's cipher preference order is used rather than the client's.
Performance optimization uses session caching to reduce SSL handshake overhead. The ssl_session_cache shared:SSL:10m directive creates a 10MB shared memory zone for caching SSL sessions across worker processes, while ssl_session_timeout defines how long cached sessions remain valid. A separate server block listening on port 80 performs HTTP to HTTPS redirection using return 301, ensuring all traffic uses encrypted connections. The $host and $request_uri variables preserve the destination URL during redirection.
Code Breakdown
listen 443 ssl http2 enables SSL on port 443 with HTTP/2 support.ssl_protocols TLSv1.2 TLSv1.3 disables outdated protocols for security.return 301 https://$host$request_uri redirects HTTP to HTTPS permanently.
