How to Deploy a Static Site Build to an Nginx Directory in Python

Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

25 lines
Python 3.9+
import shutil
import os
from pathlib import Path

SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")

def deploy_site(src: Path, dest: Path) -> None:
    if not src.exists():
        raise FileNotFoundError(f"Build directory not found: {src}")

    dest.mkdir(parents=True, exist_ok=True)

    for item in src.iterdir():
        target = dest / item.name
        if item.is_dir():
            shutil.rmtree(target, ignore_errors=True)
            shutil.copytree(item, target)
        else:
            shutil.copy2(item, target)

    print(f"Deployed {src} -> {dest} ({len(list(src.rglob('*')))} files)")

if __name__ == "__main__":
    deploy_site(SRC_DIR, DEST_DIR)

Output

stdout
Deployed build -> /var/www/html (120 files)

How it works

This script uses pathlib.Path for cross-platform path handling. src.iterdir() yields each item in the build directory; directories are copied recursively with shutil.copytree, while files are copied preserving metadata with shutil.copy2. Before copying a directory, it removes any existing destination to avoid conflicts, ensuring a clean deploy. Running the script under __main__ guard allows it to be imported without executing.

Common mistakes

  • Forgetting to create the destination directory before copying leads to FileNotFoundError.
  • Using `shutil.copy` instead of `copy2` loses file timestamps and metadata.
  • Not handling missing source directory causes unhelpful tracebacks.

Variations

  1. Use `rsync` via subprocess for incremental deployments.
  2. Zip the build and extract at the destination to reduce transfer time.

Real-world use cases

  • Automating deployment of a static site generated by a static site generator like Jekyll or Hugo.
  • Copying front-end builds to a web server in a CI/CD pipeline.
  • Syncing assets to an Nginx container for a micro-frontend hosting setup.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.