← Back to all snippets
BASH

Securely Deploy Static Website via Rsync with Configuration

Automate the deployment of a static website to a remote server using rsync, including secure SSH key authentication and configurable paths for web developers.

#!/bin/bash

# Configuration Variables
REMOTE_USER="deploy_user"
REMOTE_HOST="your_server_ip_or_hostname"
REMOTE_PATH="/var/www/your_website"
LOCAL_BUILD_PATH="./dist/" # Path to your built static files
SSH_KEY="~/.ssh/id_rsa_deploy" # Path to your SSH private key

# Check if local build path exists
if [ ! -d "$LOCAL_BUILD_PATH" ]; then
    echo "Error: Local build path '$LOCAL_BUILD_PATH' not found."
    echo "Please ensure you have built your static site (e.g., npm run build)."
    exit 1
fi

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

# Rsync command for deployment
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose output
# -z: compress file data during the transfer
# --delete: delete extra files on the receiver (remote) that are not in the sender (local)
# -e "ssh -i $SSH_KEY": specify SSH as the remote shell and use a specific identity file
rsync -avz --delete -e "ssh -i $SSH_KEY" "$LOCAL_BUILD_PATH" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

if [ $? -eq 0 ]; then
    echo "Deployment successful!"
else
    echo "Deployment failed! Check the rsync output for errors."
    exit 1
fi
How it works: This script automates the deployment of a static website using `rsync` over SSH. It configures remote server details, local build path, and an SSH key for secure authentication. It first checks for the local build directory, then executes `rsync` with archive mode, verbose output, compression, and the `--delete` option to synchronize files, ensuring the remote matches the local build.

Need help integrating this into your project?

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

Hire DigitalCodeLabs