Skip to content

Instantly share code, notes, and snippets.

@cuongdcdev
Last active July 21, 2025 16:14
Show Gist options
  • Save cuongdcdev/8ffd3b8904ed15df4086c2c35f73d7f8 to your computer and use it in GitHub Desktop.
Save cuongdcdev/8ffd3b8904ed15df4086c2c35f73d7f8 to your computer and use it in GitHub Desktop.
Automates the creation of an NGINX configuration for a virtual host that acts as a reverse proxy (Nginx as reverse proxy for Node js)
#!/bin/bash
# Introduction: This script automates the creation of an NGINX configuration for a virtual host that acts as a reverse proxy.
# It is useful for setting up an NGINX domain as a reverse proxy for your Node.js app on a self-hosted env instead of have to use Versuck or Netlifsuck.
# The script automatically configures the domain for your Node.js app with SSL, optimized to work with Cloudflare SSL.
# Before you run this script, make sure to have: Nginx + Certbot installed + configured the domain first so that Certbot can obtain the SSL certificate.
# Usage: nginx-create-site your.domain.com --proxy=127.0.0.1:3000
DOMAIN=$1
PROXY_ARG=$2
if [[ -z "$DOMAIN" || -z "$PROXY_ARG" ]]; then
echo "Usage: nginx-create-site your.domain.com --proxy=127.0.0.1:3000"
exit 1
fi
PROXY_TARGET="${PROXY_ARG#--proxy=}"
NGINX_SITES_AVAILABLE="/etc/nginx/sites-available"
NGINX_SITES_ENABLED="/etc/nginx/sites-enabled"
NGINX_CONF="$NGINX_SITES_AVAILABLE/$DOMAIN"
echo "πŸ”§ Creating NGINX config for $DOMAIN -> $PROXY_TARGET"
# Create config file
sudo tee "$NGINX_CONF" > /dev/null <<EOF
server {
listen 80;
server_name $DOMAIN;
location / {
proxy_pass http://$PROXY_TARGET;
proxy_http_version 1.1;
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;
}
}
EOF
# Enable the site
sudo ln -sf "$NGINX_CONF" "$NGINX_SITES_ENABLED/$DOMAIN"
# Reload NGINX
echo "πŸ”„ Reloading NGINX..."
sudo nginx -t && sudo systemctl reload nginx
# Install Certbot if not installed
if ! command -v certbot &> /dev/null; then
echo "πŸ“¦ Installing Certbot..."
sudo apt update
sudo apt install -y certbot python3-certbot-nginx
fi
# Get SSL Certificate
echo "πŸ” Requesting Let's Encrypt certificate for $DOMAIN..."
sudo certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos -m admin@$DOMAIN --redirect
echo "βœ… $DOMAIN is now reverse-proxying to http://$PROXY_TARGET with SSL"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment