Skip to content

Nginx Sites Backup Script

Description: This script backs up the Nginx 'sites-available' directory, compresses it with a date-stamped filename, uploads it to cloud storage via rclone, and sends email notifications for success or failure. Designed to run on Linux hosts as root or a user with sufficient privileges.

bash
#!/bin/bash

# Configuration
BACKUP_DIR="/backups/nginx"
SOURCE_DIR="/etc/nginx/sites-available"
BACKUP_FILE="nginx-sites-available-$(date +'%Y-%m-%d').tar.gz"
RCLONE_REMOTE="onedrive:/Nginx_Backups"      # Sample cloud remote
LOG_FILE="/var/log/nginx_backup.log"
EMAIL="youremail@example.com"               # Sample email

# Function to send email
send_email() {
    local subject=$1
    local message=$2
    echo -e "Subject: $subject\n\n$message" | msmtp "$EMAIL"
}

# Function to handle errors
handle_error() {
    echo "[ERROR] $1" | tee -a $LOG_FILE
    send_email "Nginx Backup Failed ❌" "Backup process failed: $1. Check logs for details."
    exit 1
}

# Start backup process
echo "Starting Nginx sites-available backup..." | tee -a $LOG_FILE

# Ensure backup directory exists
mkdir -p $BACKUP_DIR || handle_error "Failed to create backup directory."

# Compress backup
tar -czf $BACKUP_DIR/$BACKUP_FILE -C /etc/nginx/ sites-available 2>> $LOG_FILE

# Check if tar actually created the file
if [ ! -f "$BACKUP_DIR/$BACKUP_FILE" ]; then
    handle_error "Failed to create tar archive."
else
    echo "Tar archive created successfully: $BACKUP_DIR/$BACKUP_FILE" | tee -a $LOG_FILE
fi

# Upload backup to cloud storage
rclone copy $BACKUP_DIR/$BACKUP_FILE $RCLONE_REMOTE --progress 2>> $LOG_FILE
if [ $? -ne 0 ]; then
    handle_error "Failed to upload backup to cloud storage."
fi

# Send success email
send_email "Nginx Backup Successful ✅" "Nginx backup completed successfully and uploaded to $RCLONE_REMOTE."

echo "Nginx backup completed successfully and notification email sent to $EMAIL." | tee -a $LOG_FILE

# Remove local backup files
echo "Removing local backup files..."
rm -rf $BACKUP_DIR