BASH

Securely Deploy Website Files with Rsync and SSH

Master using rsync over SSH for efficient and secure deployment of website files, including excluding specific directories and verbose output for debugging.

#!/bin/bash

# --- Configuration ---
LOCAL_PATH="/path/to/your/local/project/root"
REMOTE_USER="your_ssh_user"
REMOTE_HOST="your_server_ip_or_domain"
REMOTE_PATH="/path/to/your/remote/web/root"

# Exclude files/directories (e.g., node_modules, .git, .env, editor config files)
EXCLUDES=(
    "node_modules/"
    ".git/"
    ".env"
    "*.log"
    "package-lock.json"
    "npm-debug.log"
)

# --- Script Logic ---

echo "[$(date)] Starting deployment to $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH ...";

# Build rsync exclude arguments
EXCLUDE_ARGS=""
for i in "${EXCLUDES[@]}"; do
    EXCLUDE_ARGS+="--exclude=$i "
done

# Perform rsync deployment
# -a: archive mode (recursively, preserve permissions, etc.)
# -v: verbose output
# -z: compress file data during the transfer
# -h: human-readable numbers
# --delete: delete extraneous files from destination dirs (careful with this!)
# --progress: show progress during transfer
# --rsh="ssh": use ssh as the remote shell

rsync -avzh --progress --delete $EXCLUDE_ARGS -e "ssh" "$LOCAL_PATH/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/"

if [ $? -eq 0 ]; then
    echo "[$(date)] Deployment successful!"
else
    echo "[$(date)] Deployment failed!"
    exit 1
fi

echo "[$(date)] Rsync deployment script finished."
How it works: This script uses `rsync` over SSH to efficiently deploy local website files to a remote server. The `-avzh` flags enable archive mode (preserving file attributes), verbose output, compression, and human-readable stats. The `--delete` flag ensures that files removed locally are also removed remotely (use with caution). It also demonstrates how to exclude specific files or directories, like `node_modules` or `.git` folders, to prevent unnecessary transfers and maintain a clean deployment.

Need help integrating this into your project?

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

Hire DigitalCodeLabs