How to Set Up HTTPS in Nginx: Simple Guide
To set up
HTTPS in nginx, you need to obtain an SSL certificate and configure your server block with listen 443 ssl; and paths to your ssl_certificate and ssl_certificate_key. Then reload nginx to apply the secure settings.Syntax
The basic syntax to enable HTTPS in an nginx server block includes specifying the SSL port, certificate, and key files.
listen 443 ssl;tells nginx to listen on port 443 with SSL enabled.ssl_certificatepoints to your SSL certificate file.ssl_certificate_keypoints to your private key file.
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 for HTTPS using self-signed certificates. It serves files from /var/www/html securely on port 443.
nginx
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/selfsigned.crt;
ssl_certificate_key /etc/ssl/private/selfsigned.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
root /var/www/html;
index index.html;
}
}Output
nginx: configuration file /etc/nginx/nginx.conf test is successful
Reloading nginx service applies HTTPS configuration
Common Pitfalls
Common mistakes when setting up HTTPS in nginx include:
- Using incorrect paths for
ssl_certificateorssl_certificate_key. - Not listening on port 443 or missing the
sslparameter. - Forgetting to reload or restart nginx after changes.
- Using expired or invalid SSL certificates.
- Not configuring strong SSL protocols and ciphers.
Always verify your certificate files and test nginx configuration with nginx -t before reloading.
nginx
## Wrong example (missing ssl parameter):
server {
listen 443;
server_name example.com;
ssl_certificate /etc/ssl/certs/cert.pem;
ssl_certificate_key /etc/ssl/private/key.pem;
}
## Correct example:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/cert.pem;
ssl_certificate_key /etc/ssl/private/key.pem;
}Quick Reference
Remember these key points when setting up HTTPS in nginx:
- Use
listen 443 ssl;to enable SSL on port 443. - Provide correct paths for
ssl_certificateandssl_certificate_key. - Test configuration with
nginx -tbefore reloading. - Reload nginx with
systemctl reload nginxornginx -s reload. - Use strong SSL protocols like TLS 1.2 and 1.3.
Key Takeaways
Enable SSL by adding 'listen 443 ssl;' in your nginx server block.
Specify correct paths for 'ssl_certificate' and 'ssl_certificate_key' files.
Always test nginx configuration with 'nginx -t' before reloading.
Reload nginx to apply HTTPS settings after configuration changes.
Use strong SSL protocols and ciphers for better security.