BASH

Automate Static Website Deployment via Rsync

Learn to write a Bash script for securely deploying your static website files to a remote server using Rsync over SSH, streamlining your deployment workflow and ensuring efficiency.

#!/bin/bash

# --- Configuration ---
LOCAL_BUILD_DIR="./build"  # Directory containing your static website files locally
REMOTE_USER="your_username" # SSH username for the remote server
REMOTE_HOST="your_server_ip_or_domain" # Remote server IP or domain
REMOTE_PATH="/var/www/html/your_website" # Destination path on the remote server
SSH_KEY="~/.ssh/id_rsa" # Path to your SSH private key (optional, if not using ssh-agent)

# --- Pre-deployment checks ---
if [ ! -d "${LOCAL_BUILD_DIR}" ]; then
    echo "Error: Local build directory '${LOCAL_BUILD_DIR}' not found."
    echo "Please run your build process first (e.g., npm run build, yarn build)."
    exit 1
fi

# --- Deployment Logic ---
echo "Starting deployment to ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}"

# Use rsync for more efficient and robust deployment
# -r: recursive
# -a: archive mode (preserves permissions, ownership, timestamps)
# -v: verbose
# -z: compress file data during transfer
# --delete: delete extraneous files from dest dir (useful for removing old files)
# -e ssh: specify ssh as the remote shell and use specific SSH key

rsync -ravz --delete -e "ssh -i ${SSH_KEY}" "${LOCAL_BUILD_DIR}/" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_PATH}"

if [ $? -eq 0 ]; then
    echo "Deployment successful!"
else
    echo "Deployment failed!"
    exit 1
fi
How it works: This Bash script automates the secure deployment of a static website to a remote server. It first checks for the existence of the local build directory containing the website's static files. It then uses `rsync` to efficiently copy and synchronize the contents of the local build directory to a specified path on the remote server via SSH. `rsync` is preferred over `scp` for its ability to transfer only changed files, compression (`-z`), and the `--delete` flag which ensures a clean remote deployment by removing files no longer present locally. It's configured to use an SSH key for passwordless authentication, streamlining the deployment process for web developers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs