BASH
Automating Nginx/Apache Configuration Reload
Learn to automate web server configuration reloads with a bash script. This snippet safely tests Nginx or Apache configs and reloads services, ideal for deployments.
#!/bin/bash
# Configuration file paths
NGINX_CONF_PATH="/etc/nginx/nginx.conf"
APACHE_CONF_PATH="/etc/apache2/apache2.conf" # Or /etc/httpd/conf/httpd.conf for CentOS/RHEL
# Check if Nginx is installed and running
if command -v nginx &> /dev/null; then
echo "Nginx detected. Testing configuration..."
if sudo nginx -t; then
echo "Nginx configuration test successful. Reloading Nginx service..."
sudo systemctl reload nginx
echo "Nginx reloaded."
else
echo "Nginx configuration test failed. Please check your configuration files."
exit 1
fi
# Check if Apache is installed and running
elif command -v apache2 &> /dev/null; then
echo "Apache detected. Testing configuration..."
if sudo apache2ctl configtest; then
echo "Apache configuration test successful. Reloading Apache2 service..."
sudo systemctl reload apache2
echo "Apache reloaded."
else
echo "Apache configuration test failed. Please check your configuration files."
exit 1
fi
elif command -v httpd &> /dev/null; then # For CentOS/RHEL Apache
echo "Apache (httpd) detected. Testing configuration..."
if sudo httpd -t; then
echo "Apache configuration test successful. Reloading httpd service..."
sudo systemctl reload httpd
echo "Apache (httpd) reloaded."
else
echo "Apache configuration test failed. Please check your configuration files."
exit 1
fi
else
echo "Neither Nginx nor Apache detected. Exiting."
exit 1
fi
How it works: This script automatically detects if Nginx or Apache is installed. It then performs a configuration syntax test (using `nginx -t` or `apache2ctl configtest`/`httpd -t`). If the test passes, it reloads the respective service using `systemctl reload`, applying new configurations without service downtime. If the test fails, it exits with an error.