BASH

Reload Nginx/Apache Configuration Safely

Bash script to safely reload web server configurations (Nginx or Apache) without service interruption, useful for web server management and deployment automation.

#!/bin/bash

SERVICE_NAME=""

if command -v nginx &> /dev/null; then
  SERVICE_NAME="nginx"
elif command -v apache2 &> /dev/null; then
  SERVICE_NAME="apache2"
elif command -v httpd &> /dev/null; then
  SERVICE_NAME="httpd"
fi

if [ -z "$SERVICE_NAME" ]; then
  echo "Error: No supported web server (Nginx, Apache) found."
  exit 1
fi

# Test configuration before reloading
if [ "$SERVICE_NAME" == "nginx" ]; then
  sudo nginx -t
  if [ $? -ne 0 ]; then
    echo "Nginx configuration test failed. Not reloading."
    exit 1
  fi
elif [ "$SERVICE_NAME" == "apache2" ] || [ "$SERVICE_NAME" == "httpd" ]; then
  sudo apachectl configtest
  if [ $? -ne 0 ]; then
    echo "Apache configuration test failed. Not reloading."
    exit 1
  fi
fi

# Reload service
echo "Reloading $SERVICE_NAME service..."
sudo systemctl reload "$SERVICE_NAME"

if [ $? -eq 0 ]; then
  echo "$SERVICE_NAME configuration reloaded successfully."
else
  echo "Failed to reload $SERVICE_NAME configuration."
  exit 1
fi
How it works: This script first detects if Nginx or Apache is installed on the system. Before attempting a reload, it performs a configuration test for the detected web server. If the test passes, it then safely reloads the service using `systemctl reload`. This approach prevents deploying broken configurations and ensures continuous web server availability, making it ideal for deployment pipelines.

Need help integrating this into your project?

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

Hire DigitalCodeLabs