Skip to content

Instantly share code, notes, and snippets.

@miiiladiii244
Created February 21, 2025 17:21
Show Gist options
  • Save miiiladiii244/b2cdfa690c4270ec11916435894305b4 to your computer and use it in GitHub Desktop.
Save miiiladiii244/b2cdfa690c4270ec11916435894305b4 to your computer and use it in GitHub Desktop.
A bash script to setup nginx as reverse proxy to $BACKEND
#!/bin/bash
set -e
# Variable for the backend service address.
BACKEND="127.0.0.1:8000"
# Echo the purpose of this script.
echo "This script installs Nginx, creates a self-signed SSL certificate, and configures Nginx as a reverse proxy to forward HTTPS requests to the backend service at ${BACKEND}."
echo "Updating package index and installing nginx and openssl..."
sudo apt update
sudo apt install -y nginx openssl
echo "Creating SSL directory..."
sudo mkdir -p /etc/nginx/ssl
# Generate a self-signed certificate valid for 365 days.
if [ ! -f /etc/nginx/ssl/nginx-selfsigned.crt ]; then
echo "Generating self-signed certificate..."
sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/nginx/ssl/nginx-selfsigned.key \
-out /etc/nginx/ssl/nginx-selfsigned.crt \
-subj "/CN=localhost"
fi
echo "Configuring Nginx as a reverse proxy..."
# Use sudo tee to write the configuration file into /etc/nginx/sites-available.
sudo tee /etc/nginx/sites-available/reverse-proxy > /dev/null <<EOF
server {
listen 80;
server_name localhost;
# Redirect all HTTP traffic to HTTPS.
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl;
server_name localhost;
# SSL configuration using the self-signed certificate.
ssl_certificate /etc/nginx/ssl/nginx-selfsigned.crt;
ssl_certificate_key /etc/nginx/ssl/nginx-selfsigned.key;
# Reverse proxy configuration.
location / {
proxy_pass http://${BACKEND};
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
}
}
EOF
echo "Enabling the new configuration..."
sudo ln -sf /etc/nginx/sites-available/reverse-proxy /etc/nginx/sites-enabled/reverse-proxy
# Optionally remove the default site if it exists.
if [ -f /etc/nginx/sites-enabled/default ]; then
sudo rm /etc/nginx/sites-enabled/default
fi
echo "Testing Nginx configuration..."
sudo nginx -t
echo "Reloading Nginx..."
sudo systemctl reload nginx
echo "Nginx is now installed and configured as a reverse proxy with a self-signed certificate for the backend at ${BACKEND}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment