How to Use SSL Certificate in Nginx: Simple Setup Guide
To use an
SSL certificate in nginx, configure the server block with listen 443 ssl; and specify the paths to your ssl_certificate and ssl_certificate_key files. This enables HTTPS by telling nginx where to find your SSL files and to listen on the secure port 443.Syntax
The basic syntax to enable SSL in nginx involves these directives inside a server block:
listen 443 ssl;- tells nginx to listen on port 443 with SSL enabled.ssl_certificate- path to your SSL certificate file (usually .crt or .pem).ssl_certificate_key- path to your private key file (usually .key).
These settings tell nginx to use your SSL certificate and key to secure connections.
nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
root /var/www/html;
index index.html;
}
}Example
This example shows a complete nginx server block configured to serve HTTPS using SSL certificate and key files. It listens on port 443 and serves files from /var/www/html.
nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
location / {
root /var/www/html;
index index.html;
}
}Output
When nginx is reloaded with this config, it will serve HTTPS traffic on https://example.com using the specified SSL certificate and key.
Common Pitfalls
Common mistakes when using SSL in nginx include:
- Using incorrect file paths for
ssl_certificateorssl_certificate_key. - Not including
listen 443 ssl;which disables SSL on port 443. - Forgetting to reload or restart nginx after changes.
- Using a certificate and key that do not match.
- Not setting up a redirect from HTTP (port 80) to HTTPS (port 443) for better security.
Always check nginx error logs if SSL does not work.
nginx
server {
listen 80;
server_name example.com;
# Redirect all HTTP requests to HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
location / {
root /var/www/html;
index index.html;
}
}Output
This config redirects HTTP traffic to HTTPS and serves secure content correctly, avoiding common SSL pitfalls.
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 certificate file path. - Set
ssl_certificate_keyto your private key file path. - Reload nginx after changes with
sudo nginx -s reload. - Redirect HTTP to HTTPS for better security.
Key Takeaways
Enable SSL in nginx by adding 'listen 443 ssl;' in the server block.
Specify correct paths for 'ssl_certificate' and 'ssl_certificate_key' files.
Always reload nginx after updating SSL configuration.
Redirect HTTP traffic to HTTPS to enforce secure connections.
Check nginx error logs if SSL does not work as expected.