How to set up Nginx with Let's Encrypt for automatic SSL certificate renewal?

To set up Nginx with Let's Encrypt for automatic SSL certificate renewal, follow these steps:

  1. Install the Certbot tool:

    • On Ubuntu or Debian: sudo apt-get install certbot
    • On CentOS or Red Hat: sudo yum install certbot
    • On FreeBSD: sudo pkg install certbot
  2. Generate the initial SSL certificate using Certbot:

    • Run the following command: sudo certbot certonly --nginx -d example.com -d www.example.com
    • Make sure to replace example.com with your own domain name(s)
  3. Configure Nginx to use the SSL certificate:

    • Open the Nginx server block configuration file for your website: sudo nano /etc/nginx/sites-available/example.com
    • Add the following lines within the server block: listen 443 ssl; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; Note: Replace example.com with your own domain name
  4. Test the Nginx configuration and restart Nginx:

    • Run the following command to test the configuration: sudo nginx -t
    • If the test is successful, restart Nginx: sudo systemctl restart nginx
  5. Set up automatic certificate renewal using a cron job:

    • Open the crontab for the root user: sudo crontab -e
    • Add the following line to run the renewal command twice daily: 0 0,12 * * * certbot renew --post-hook "systemctl reload nginx"
    • Save and exit the crontab file
  6. Verify automatic renewal:

    • Run the following command to test the renewal process: sudo certbot renew --dry-run
    • If the dry-run command runs successfully without any errors, the automatic renewal is configured properly

That's it! Your Nginx server is now set up with Let's Encrypt SSL certificate and automatic renewal.