← Back to all snippets
BASH

Generating Dynamic Nginx Virtual Host Configuration

Learn to dynamically generate Nginx virtual host configuration files using a Bash script, useful for automating the setup of new web projects or domains.

#!/bin/bash
# --- Configuration Variables ---
DOMAIN="example.com"
SERVER_PORT="80"
ROOT_PATH="/var/www/${DOMAIN}/html"
LOGS_PATH="/var/log/nginx/${DOMAIN}"
CONF_FILE="/etc/nginx/sites-available/${DOMAIN}.conf"

# Ensure log directory exists
mkdir -p "${LOGS_PATH}"

# Generate Nginx Virtual Host Configuration using a here-document
cat > "${CONF_FILE}" << EOF
server {
    listen ${SERVER_PORT};
    server_name ${DOMAIN} www.${DOMAIN};

    root ${ROOT_PATH};
    index index.html index.htm;

    access_log ${LOGS_PATH}/access.log;
    error_log ${LOGS_PATH}/error.log;

    location / {
        try_files \$uri \$uri/ =404;
    }

    # Add more Nginx configuration here as needed
}
EOF

if [ $? -eq 0 ]; then
    echo "Nginx virtual host configuration for ${DOMAIN} generated at ${CONF_FILE}"
    echo "Remember to link it to sites-enabled: sudo ln -s ${CONF_FILE} /etc/nginx/sites-enabled/"
    echo "And restart Nginx: sudo systemctl reload nginx"
else
    echo "Error: Failed to generate Nginx configuration." >&2
    exit 1
fi
How it works: This script demonstrates how to dynamically generate an Nginx virtual host configuration file using a Bash "here-document" (heredoc). It defines variables for the domain, port, root path, log paths, and the output configuration file. The `cat > "${CONF_FILE}" << EOF` construct allows writing multiline text into a file, with shell variables being expanded within the heredoc. This is highly useful for automating the setup of new domains or web applications, ensuring consistent configurations. After generation, instructions for enabling and restarting Nginx are provided.

Need help integrating this into your project?

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

Hire DigitalCodeLabs