#!/bin/bash DOMAIN=$1 TARGET=$2 PATTERNS=$3 REAL_IP_OVERRIDE=$4 HOSTS_LINE="127.0.0.1 $DOMAIN" NGINX_CONF=$(mktemp) CERT_DIR=$(pwd) CLEANUP_DONE=0 # Resolve real IP before we mess with hosts if [ -n "$REAL_IP_OVERRIDE" ]; then REAL_IP="$REAL_IP_OVERRIDE" echo "Using provided IP: $REAL_IP" else # Use external DNS (8.8.8.8) to bypass /etc/hosts # Get final IP (not CNAME) by filtering for IP addresses only REAL_IP=$(dig +short "$DOMAIN" @8.8.8.8 | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -n1) if [ -z "$REAL_IP" ]; then echo "Could not resolve $DOMAIN" exit 1 fi # Check if resolved IP is localhost (proxy loop) if [[ "$REAL_IP" == "127.0.0.1" || "$REAL_IP" == "::1" || "$REAL_IP" == "localhost" ]]; then echo "ERROR: $DOMAIN resolves to localhost ($REAL_IP)" echo "This would cause a proxy loop." echo "Provide the real IP as the 4th argument:" echo " $0 $DOMAIN $TARGET \"$PATTERNS\" " exit 1 fi echo "Resolved $DOMAIN to $REAL_IP" fi cleanup() { [ "$CLEANUP_DONE" -eq 1 ] && return CLEANUP_DONE=1 echo "Cleaning up..." if [[ "$OSTYPE" == "darwin"* ]]; then sudo sed -i "" "\|$HOSTS_LINE|d" /etc/hosts else sudo sed -i "\|$HOSTS_LINE|d" /etc/hosts fi rm -f "$DOMAIN.pem" "$DOMAIN-key.pem" "$NGINX_CONF" echo "Done" } trap cleanup EXIT echo "$HOSTS_LINE" | sudo tee -a /etc/hosts mkcert "$DOMAIN" # Build passthrough location blocks PASSTHROUGH_LOCATIONS="" if [ -n "$PATTERNS" ]; then IFS=',' read -ra PATTERN_ARRAY <<< "$PATTERNS" for pattern in "${PATTERN_ARRAY[@]}"; do # Remove trailing * from pattern if present clean_pattern="${pattern%\*}" PASSTHROUGH_LOCATIONS+=" # Passthrough for /${clean_pattern} location ~* ^/${clean_pattern} { proxy_pass https://$REAL_IP; proxy_ssl_server_name on; proxy_ssl_name $DOMAIN; proxy_set_header Host \$host; proxy_set_header X-Real-IP \$remote_addr; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto \$scheme; proxy_http_version 1.1; proxy_set_header Connection \"\"; } " done fi cat > "$NGINX_CONF" <