Avoid breaking live sites with an nginx safe reload script — runs nginx -t, backs up config, and only reloads when syntax is valid.
What this script does
- Runs nginx -t before any reload
- Backs up /etc/nginx to timestamped tarball
- Reloads only when test passes
- Email alert on config syntax failure
- Logs result for change management audit
Prerequisites
- Nginx installed
- Root or sudo access
- Optional: mail for alerts
Step 1: Save the script
sudo nano /usr/local/bin/nginx-safe-reload.sh
sudo chmod +x /usr/local/bin/nginx-safe-reload.sh
Step 2: Full script (scroll to read)
nginx-safe-reload.sh
#!/usr/bin/env bash
set -euo pipefail
NGINX_BIN="/usr/sbin/nginx"
CONFIG_DIR="/etc/nginx"
BACKUP_DIR="/var/backups/nginx-config"
ALERT_EMAIL="[email protected]"
LOG="/var/log/nginx-reload.log"
log(){ echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }
mkdir -p "$BACKUP_DIR"
log "Testing nginx configuration..."
if $NGINX_BIN -t >> "$LOG" 2>&1; then
ARCHIVE="${BACKUP_DIR}/nginx_$(date +%F_%H-%M-%S).tar.gz"
tar -czf "$ARCHIVE" -C / etc/nginx 2>/dev/null || tar -czf "$ARCHIVE" "$CONFIG_DIR"
log "Config OK — backup saved: $ARCHIVE"
systemctl reload nginx || $NGINX_BIN -s reload
log "Nginx reloaded successfully"
else
log "ERROR: nginx -t failed — reload aborted"
[[ -n "$ALERT_EMAIL" ]] && command -v mail >/dev/null && \
tail -20 "$LOG" | mail -s "Nginx config FAILED: $(hostname -s)" "$ALERT_EMAIL"
exit 1
fi
Scroll inside the box to read the full script.
Step 3: Configure settings
NGINX_BIN— path to nginx binaryCONFIG_DIR— default /etc/nginxALERT_EMAIL— notify on test failure

Step 4: Test manually
nginx -t
sudo /usr/local/bin/nginx-safe-reload.sh
Related tutorials
- Linux Backup Shell Script: Files & Database to Remote Server
- Cron Jobs in Linux: Schedule Tasks with crontab
- SSH Key Authentication on Linux Servers
Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).