← Back to all snippets
BASH

Automate Static Website Deployment via SCP

Streamline static website deployment to a remote server using a simple bash script that utilizes SCP for efficient and secure file transfer.

#!/bin/bash

LOCAL_BUILD_DIR="./dist" # Local directory containing your built static files
REMOTE_USER="webuser"
REMOTE_HOST="your-server.com"
REMOTE_PATH="/var/www/your-website/" # Remote directory where files will be deployed

# Check if local build directory exists
if [ ! -d "$LOCAL_BUILD_DIR" ]; then
    echo "Error: Local build directory '$LOCAL_BUILD_DIR' not found."
    echo "Please build your project first (e.g., npm run build)."
    exit 1
fi

echo "Deploying static website from '$LOCAL_BUILD_DIR' to '$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH'..."

# Use scp to transfer files
# -r: recursive (for directories)
# -p: preserves modification times, access times, and modes from the original file
# -q: quiet mode (don't display progress meter)
scp -rpq "$LOCAL_BUILD_DIR"/* "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"

if [ $? -eq 0 ]; then
    echo "Deployment successful!"
    # Optional: SSH into the server to clear cache or restart service if needed
    # ssh "$REMOTE_USER@$REMOTE_HOST" "sudo systemctl reload nginx"
else
    echo "Deployment failed. Please check network connectivity, permissions, or paths."
    exit 1
fi
How it works: This script automates the deployment of a static website. It defines local and remote paths for the website's build directory and the target server. It then uses `scp -rpq` to securely copy files recursively, preserving file attributes, from the local build directory to a specified remote server location. The script includes a check for the local build directory and provides clear success or failure messages, greatly simplifying the deployment process for static sites.

Need help integrating this into your project?

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

Hire DigitalCodeLabs