BASH

Deploy Website Files via Rsync over SSH

A robust Bash script to securely deploy website files to a remote server using rsync over SSH, ensuring only changed files are transferred efficiently.

#!/bin/bash

# --- Configuration ---
LOCAL_PATH="/path/to/local/website/project/"
REMOTE_USER="remote_user"             # SSH username for the remote server
REMOTE_HOST="your_server_ip_or_domain" # IP address or domain of the remote server
REMOTE_PATH="/var/www/html/your_website/" # Destination path on the remote server
EXCLUDE_FILE="/path/to/local/website/project/.rsync-exclude.txt" # Path to a file listing items to exclude
# ---------------------

# Example .rsync-exclude.txt content:
# .git
# .env
# node_modules/
# vendor/
# storage/*.log
# .DS_Store

echo "Starting deployment to $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH..."

# Ensure the remote deployment directory exists
ssh "$REMOTE_USER@$REMOTE_HOST" "mkdir -p '$REMOTE_PATH'"

# Use rsync over ssh to efficiently sync files
# -a: archive mode (recursively copy, preserve attributes, etc.)
# -v: verbose output
# -z: compress file data during transfer
# --delete: delete extraneous files from dest dirs (not in src)
# --exclude-from: use a file to specify exclude patterns
rsync -avz --delete --exclude-from="$EXCLUDE_FILE" "$LOCAL_PATH" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

if [ $? -eq 0 ]; then
    echo "Deployment successful!"
else
    echo "Deployment failed! Please check your rsync command and permissions." >&2
    exit 1
fi

echo "Deployment process completed."
exit 0
How it works: This script automates website file deployments using `rsync` over SSH, a highly efficient method as it only transfers changed files. It's configured with local and remote paths, SSH credentials, and specifies an exclude file (e.g., `.rsync-exclude.txt`) to prevent transferring development artifacts like `.git` folders or `node_modules`. The `ssh` command first ensures the remote destination directory exists. Then, `rsync` with options `-avz --delete --exclude-from` performs the synchronization, providing verbose output and compression for faster transfers, while also deleting files on the remote that are no longer present locally. Error handling is included to report deployment status.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs