How to Configure SSL in Nginx: Simple Steps
To configure
SSL in nginx, you need to specify the ssl_certificate and ssl_certificate_key directives inside a server block listening on port 443. This enables HTTPS by providing the path to your SSL certificate and private key files.Syntax
The basic syntax to enable SSL in an nginx server block includes these directives:
listen 443 ssl;- tells nginx to listen on port 443 with SSL enabled.ssl_certificate- path to your SSL certificate file.ssl_certificate_key- path to your private key file.
These directives must be inside a server block.
nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
location / {
root /var/www/html;
index index.html;
}
}Example
This example shows a complete nginx server block configured for SSL using self-signed certificates. It listens on port 443 and serves files from /var/www/html.
nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
root /var/www/html;
index index.html;
}
}Output
nginx starts successfully and serves HTTPS requests on https://example.com
Common Pitfalls
Common mistakes when configuring SSL in nginx include:
- Forgetting to include
listen 443 ssl;which disables SSL on port 443. - Using incorrect paths for
ssl_certificateorssl_certificate_keyfiles. - Not reloading nginx after configuration changes.
- Missing intermediate certificates in the
ssl_certificatefile, causing browser trust errors.
Always check nginx error logs if SSL does not work.
nginx
server {
listen 443;
server_name example.com;
ssl_certificate /wrong/path/cert.crt;
ssl_certificate_key /wrong/path/key.key;
location / {
root /var/www/html;
}
}
# Corrected version:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
location / {
root /var/www/html;
}
}Quick Reference
Remember these key points when configuring SSL in nginx:
- Use
listen 443 ssl;to enable SSL on port 443. - Set
ssl_certificateto your full certificate chain file. - Set
ssl_certificate_keyto your private key file. - Reload nginx after changes with
sudo nginx -s reload. - Test your configuration with
nginx -tbefore reloading.
Key Takeaways
Always specify
listen 443 ssl; in your server block to enable SSL.Provide correct paths for
ssl_certificate and ssl_certificate_key files.Reload nginx after configuration changes using
sudo nginx -s reload.Include the full certificate chain in
ssl_certificate to avoid browser errors.Test your nginx config with
nginx -t before reloading to catch errors.