Nginx Config Test and Safe Reload Shell Script for Linux

nginx reload shell script

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 binary
  • CONFIG_DIR — default /etc/nginx
  • ALERT_EMAIL — notify on test failure
Nginx config test and reload shell script Linux
Nginx config test and reload shell script Linux

Step 4: Test manually

nginx -t
sudo /usr/local/bin/nginx-safe-reload.sh

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).