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.
Python code
25 linesimport 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
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
- Use `rsync` via subprocess for incremental deployments.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.