Веб-Сервер Средний

Автоматическая Настройка SSL/TLS для Nginx

Устанавливает бесплатный SSL/TLS сертификат с Let's Encrypt на веб-сервере Nginx и настраивает автоматическое обновление.

Опубликовано: 15.02.2024 Обновлено: 05.12.2024

Код

#!/bin/bash

# Nginx SSL/TLS Auto Setup with Let's Encrypt

if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root"
    exit 1
fi

read -p "Enter your domain name: " DOMAIN
read -p "Enter your email: " EMAIL

echo ""
echo "Setting up SSL for $DOMAIN"
echo ""

if ! command -v certbot &> /dev/null; then
    echo "Installing certbot..."
    apt-get update
    apt-get install -y certbot python3-certbot-nginx
fi

if ! systemctl is-active --quiet nginx; then
    echo "Starting nginx..."
    systemctl start nginx
fi

NGINX_CONF="/etc/nginx/sites-available/$DOMAIN"

cat > "$NGINX_CONF" <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN www.$DOMAIN;
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
EOF

ln -sf "$NGINX_CONF" /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx

echo "✓ Nginx configuration created"
echo ""

echo "Obtaining SSL certificate..."
certbot --nginx -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos --email "$EMAIL" --redirect

if [ $? -eq 0 ]; then
    echo "✓ SSL certificate installed successfully"
    echo ""
    
    echo "Testing automatic renewal..."
    certbot renew --dry-run
    
    if [ $? -eq 0 ]; then
        echo "✓ Automatic renewal is configured"
    else
        echo "⚠️  Warning: Automatic renewal test failed"
    fi
else
    echo "✗ Failed to obtain SSL certificate"
    exit 1
fi

echo ""
echo "======================================"
echo "SSL Setup Complete!"
echo "======================================"
echo "Your site is now available at:"
echo "https://$DOMAIN"
echo ""
echo "Certificate will auto-renew before expiration"
echo "You can manually renew with: certbot renew"

Использование

# Run as root
sudo chmod +x nginx_ssl_setup.sh
sudo ./nginx_ssl_setup.sh

# Enter your domain and email
# Script will automatically setup SSL

Теги

nginx ssl https lets encrypt certbot