BASH
Modify Nginx Config with sed for Deployment
Automate common Nginx configuration changes using `sed` in Bash, such as updating server names or proxy passes, simplifying deployment tasks.
#!/bin/bash
NGINX_CONF="/etc/nginx/sites-available/default" # Path to your Nginx config
OLD_SERVER_NAME="example.com"
NEW_SERVER_NAME="newapp.com"
OLD_PROXY_PASS="http://localhost:8000"
NEW_PROXY_PASS="http://localhost:3000"
# Make a backup of the original config first
cp "${NGINX_CONF}" "${NGINX_CONF}.bak_$(date +%Y%m%d%H%M%S)"
echo "Updating server_name from ${OLD_SERVER_NAME} to ${NEW_SERVER_NAME}..."
sed -i "s/server_name ${OLD_SERVER_NAME};/server_name ${NEW_SERVER_NAME};/g" "${NGINX_CONF}"
echo "Updating proxy_pass from ${OLD_PROXY_PASS} to ${NEW_PROXY_PASS}..."
sed -i "s|proxy_pass ${OLD_PROXY_PASS};|proxy_pass ${NEW_PROXY_PASS};|g" "${NGINX_CONF}"
if [ $? -eq 0 ]; then
echo "Nginx configuration updated successfully. Please restart Nginx to apply changes."
echo "sudo systemctl restart nginx"
else
echo "Failed to update Nginx configuration."
exit 1
fi
How it works: This script shows how to use `sed` to programmatically modify an Nginx configuration file. It first backs up the original file. Then, it uses `sed -i` to perform in-place substitutions for `server_name` and `proxy_pass` directives. Note the use of `|` as a delimiter in the second `sed` command to avoid issues with `/` in URLs.