BASH

Graceful Reload of Web Server (Nginx/Apache)

Gracefully reload Nginx or Apache configuration without dropping active connections, essential for applying changes to web servers in production environments.

#!/bin/bash

# Check if running as root (required for systemctl commands)
if [[ $EUID -ne 0 ]]; then
   echo "Error: This script must be run as root or with sudo." >&2
   exit 1
fi

echo "Attempting to gracefully reload web server configuration..."

# Check for Nginx and reload if found
if command -v nginx &> /dev/null; then
    echo "Nginx detected. Attempting graceful reload..."
    systemctl reload nginx
    if [ $? -eq 0 ]; then
        echo "Nginx reloaded successfully."
    else
        echo "Failed to reload Nginx. Check system logs for details." >&2
        exit 1
    fi
# Check for Apache2 (Debian/Ubuntu) and reload if found
elif command -v apache2 &> /dev/null; then
    echo "Apache2 detected. Attempting graceful reload..."
    systemctl reload apache2
    if [ $? -eq 0 ]; then
        echo "Apache2 reloaded successfully."
    else
        echo "Failed to reload Apache2. Check system logs for details." >&2
        exit 1
    fi
# Check for Apache (RHEL/CentOS httpd) and reload if found
elif command -v httpd &> /dev/null; then
    echo "Apache (httpd) detected. Attempting graceful reload..."
    systemctl reload httpd
    if [ $? -eq 0 ]; then
        echo "Apache (httpd) reloaded successfully."
    else
        echo "Failed to reload Apache (httpd). Check system logs for details." >&2
        exit 1
    fi
else
    echo "Neither Nginx nor Apache web server found. No action taken." >&2
    exit 1
fi
How it works: This script automates the graceful reloading of common web servers like Nginx or Apache. It first checks for root privileges, then detects which web server is active on the system. It then issues a `systemctl reload` command, which applies new configurations (e.g., virtual host changes) without interrupting active client connections, making it ideal for applying changes in production environments without service interruption.

Need help integrating this into your project?

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

Hire DigitalCodeLabs