+
jwt
+
+
vault
0b
strapi
+
+
jasmine
koa
adonis
+
macos
pytest
%
+
+
+
clj
+
+
express
+
ฯ€
svelte
bsd
+
neo4j
+
+
+
#
{}
+
remix
+
==
+
<=
+
elixir
websocket
xgboost
+
clickhouse
+
arch
android
#
+
โˆˆ
+
jax
+
+
hugging
+
sklearn
+
kali
node
!=
+
+
+
alpine
ocaml
+
kotlin
php
pascal
prettier
+
gin
โˆ‘
deno
firebase
+
+
+
&&
netlify
+
+
+
โˆ‚
+
rails
+
Back to Blog
๐Ÿ”„ AlmaLinux Reverse Proxy Setup: Complete Nginx Gateway Configuration Guide
AlmaLinux Nginx Reverse Proxy

๐Ÿ”„ AlmaLinux Reverse Proxy Setup: Complete Nginx Gateway Configuration Guide

Published Sep 17, 2025

Master AlmaLinux Nginx reverse proxy configuration for modern web architecture! Learn upstream servers, SSL termination, caching, API gateway setup, microservices routing, and enterprise-grade proxy deployment.

46 min read
0 views
Table of Contents

๐Ÿ”„ AlmaLinux Reverse Proxy Setup: Complete Nginx Gateway Configuration Guide

Welcome to the comprehensive AlmaLinux Nginx reverse proxy configuration guide! ๐ŸŽ‰ A reverse proxy is the backbone of modern web architecture, acting as an intelligent gateway that sits between clients and your backend services. Whether youโ€™re building a microservices architecture, implementing API gateways, or creating scalable web applications, Nginx reverse proxy provides the performance, security, and flexibility you need! ๐ŸŒŸ

Setting up a reverse proxy might seem complex, but itโ€™s actually one of the most powerful tools in modern web infrastructure. By the end of this guide, youโ€™ll have a robust Nginx reverse proxy that can handle SSL termination, load balancing, caching, and intelligent routing for enterprise-grade applications! ๐Ÿš€

๐Ÿค” Why is Reverse Proxy Important?

Reverse proxies are absolutely essential for modern web architecture! Hereโ€™s why setting up Nginx as a reverse proxy is incredibly valuable: โœจ

  • ๐Ÿ›ก๏ธ Security Layer: Hide backend servers and add security filtering at the edge
  • โšก Performance Boost: Cache responses and reduce backend server load
  • ๐Ÿ” SSL Termination: Handle encryption/decryption centrally for all services
  • ๐Ÿ“ˆ Load Distribution: Intelligently distribute traffic across multiple backend servers
  • ๐ŸŒ API Gateway: Centralize API management, authentication, and rate limiting
  • ๐ŸŽฏ Request Routing: Route requests based on URL, headers, or geographic location
  • ๐Ÿ’พ Compression: Compress responses to reduce bandwidth usage
  • ๐Ÿ”„ Health Monitoring: Monitor backend server health and route around failures
  • ๐Ÿ“Š Analytics: Centralized logging and monitoring for all web traffic
  • ๐Ÿš€ Scalability: Enable horizontal scaling without client-side changes

๐ŸŽฏ What You Need

Before we start building your Nginx reverse proxy, make sure you have these essentials ready:

โœ… AlmaLinux 9.x server with root or sudo access โœ… Minimum 2GB RAM and 10GB disk space โœ… Static IP address for the proxy server โœ… Backend servers to proxy requests to โœ… Basic networking knowledge (weโ€™ll guide you through everything!) โœ… Terminal/SSH access to your server โœ… Text editor familiarity (nano, vim, or gedit) โœ… Firewall admin access for port configuration โœ… SSL certificates (optional but recommended) โœ… Domain names pointing to your proxy server

๐Ÿ“ Step 1: System Preparation and Nginx Installation

Letโ€™s start by preparing your AlmaLinux system and installing Nginx! ๐ŸŽฏ

# Update system packages to latest versions
sudo dnf update -y

# Install Nginx web server
sudo dnf install -y nginx

# Install additional tools for SSL and monitoring
sudo dnf install -y openssl curl wget htop

# Install network utilities for troubleshooting
sudo dnf install -y net-tools tcpdump nmap telnet

# Check installed Nginx version
nginx -v

# Check Nginx modules
nginx -V 2>&1 | grep -o with-[a-z_-]*

# Verify system resources
free -h
df -h

# Check network configuration
ip addr show
hostname -f

# Test network connectivity
ping -c 3 google.com

# Check if any web server is already running
sudo ss -tlnp | grep -E ":80|:443"

Expected output:

Complete!
nginx version: nginx/1.20.1
with-http_ssl_module
with-http_realip_module
with-http_addition_module
with-http_sub_module
with-http_dav_module
with-http_flv_module
with-http_mp4_module
with-http_gunzip_module
with-http_gzip_static_module

              total        used        free      shared  buff/cache   available
Mem:           2.0Gi       350Mi       1.3Gi        12Mi       320Mi       1.4Gi

Perfect! ๐ŸŒŸ Nginx is installed with all necessary modules for reverse proxy functionality!

๐Ÿ”ง Step 2: Configure Basic Reverse Proxy

Create a comprehensive Nginx reverse proxy configuration! โšก

# Backup original Nginx configuration
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup

# Create new main Nginx configuration
sudo tee /etc/nginx/nginx.conf << 'EOF'
# Nginx Reverse Proxy Configuration

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;

# Load dynamic modules
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    # Basic settings
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    # Enhanced log format for reverse proxy
    log_format proxy '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for" '
                     'rt=$request_time uct="$upstream_connect_time" '
                     'uht="$upstream_header_time" urt="$upstream_response_time"';

    access_log /var/log/nginx/access.log proxy;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 4096;
    server_tokens off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 10240;
    gzip_proxied expired no-cache no-store private must-revalidate auth;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/x-javascript
        application/javascript
        application/xml+rss
        application/json;

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;

    # Upstream backend servers
    upstream backend_web {
        least_conn;
        server 192.168.1.101:8080 weight=3 max_fails=3 fail_timeout=30s;
        server 192.168.1.102:8080 weight=3 max_fails=3 fail_timeout=30s;
        server 192.168.1.103:8080 weight=1 max_fails=3 fail_timeout=30s backup;
        keepalive 32;
    }

    upstream backend_api {
        least_conn;
        server 192.168.1.111:3000 weight=5 max_fails=2 fail_timeout=20s;
        server 192.168.1.112:3000 weight=5 max_fails=2 fail_timeout=20s;
        server 192.168.1.113:3000 weight=3 max_fails=2 fail_timeout=20s;
        keepalive 64;
    }

    upstream backend_static {
        server 192.168.1.121:80 weight=1;
        server 192.168.1.122:80 weight=1;
        keepalive 16;
    }

    # SSL configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # Include server configurations
    include /etc/nginx/conf.d/*.conf;
}
EOF

# Create the main reverse proxy server configuration
sudo tee /etc/nginx/conf.d/reverse-proxy.conf << 'EOF'
# Main Reverse Proxy Server Configuration

# HTTP to HTTPS redirect
server {
    listen 80;
    server_name _;
    return 301 https://$host$request_uri;
}

# Main HTTPS reverse proxy
server {
    listen 443 ssl http2;
    server_name proxy.company.local;

    # SSL certificates
    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Main web application
    location / {
        proxy_pass http://backend_web;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_cache_bypass $http_upgrade;

        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # Buffer settings
        proxy_buffer_size 4k;
        proxy_buffers 100 8k;
        proxy_busy_buffers_size 16k;
        proxy_temp_file_write_size 64k;
    }

    # API endpoints with rate limiting
    location /api/ {
        limit_req zone=api burst=20 nodelay;

        proxy_pass http://backend_api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_cache_bypass $http_upgrade;

        # API-specific timeouts
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }

    # Static content with caching
    location /static/ {
        proxy_pass http://backend_static/;
        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;

        # Caching for static content
        proxy_cache static_cache;
        proxy_cache_valid 200 301 302 1h;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout invalid_header updating;
        add_header X-Cache-Status $upstream_cache_status;

        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Health check endpoint
    location /nginx-health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }
}

# Cache configuration
proxy_cache_path /var/cache/nginx/static levels=1:2 keys_zone=static_cache:10m inactive=60m use_temp_path=off;
EOF

# Test Nginx configuration syntax
sudo nginx -t

# Create necessary directories
sudo mkdir -p /var/cache/nginx/static
sudo mkdir -p /etc/ssl/nginx

# Set proper ownership
sudo chown -R nginx:nginx /var/cache/nginx/

Expected output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Excellent! โœ… Basic reverse proxy configuration is created and validated!

๐ŸŒŸ Step 3: Configure SSL/TLS Termination

Set up SSL certificates and secure connections for the reverse proxy! ๐Ÿ”

# Generate self-signed SSL certificate for testing
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
    -keyout /etc/ssl/nginx/nginx.key \
    -out /etc/ssl/nginx/nginx.crt \
    -subj "/C=US/ST=State/L=City/O=Company/OU=IT Department/CN=$(hostname -f)"

# Set secure permissions for SSL files
sudo chmod 600 /etc/ssl/nginx/nginx.key
sudo chmod 644 /etc/ssl/nginx/nginx.crt
sudo chown root:root /etc/ssl/nginx/nginx.*

# Create SSL certificate management script
sudo tee /usr/local/bin/manage-proxy-ssl.sh << 'EOF'
#!/bin/bash
# SSL Certificate Management for Nginx Reverse Proxy

CERT_DIR="/etc/ssl/nginx"
DOMAIN="$2"

case "$1" in
    generate)
        if [ -z "$DOMAIN" ]; then
            echo "Usage: $0 generate <domain>"
            exit 1
        fi

        echo "Generating SSL certificate for $DOMAIN..."

        # Generate private key
        openssl genrsa -out "$CERT_DIR/${DOMAIN}.key" 2048

        # Generate certificate signing request
        openssl req -new -key "$CERT_DIR/${DOMAIN}.key" \
            -out "$CERT_DIR/${DOMAIN}.csr" \
            -subj "/C=US/ST=State/L=City/O=Company/CN=$DOMAIN"

        # Generate self-signed certificate
        openssl x509 -req -days 365 \
            -in "$CERT_DIR/${DOMAIN}.csr" \
            -signkey "$CERT_DIR/${DOMAIN}.key" \
            -out "$CERT_DIR/${DOMAIN}.crt"

        # Set permissions
        chmod 600 "$CERT_DIR/${DOMAIN}.key"
        chmod 644 "$CERT_DIR/${DOMAIN}.crt"

        echo "Certificate generated for $DOMAIN"
        ;;

    install)
        if [ -z "$DOMAIN" ]; then
            echo "Usage: $0 install <domain>"
            echo "Place certificate in /tmp/${DOMAIN}.crt and key in /tmp/${DOMAIN}.key"
            exit 1
        fi

        if [ ! -f "/tmp/${DOMAIN}.crt" ] || [ ! -f "/tmp/${DOMAIN}.key" ]; then
            echo "Certificate files not found in /tmp/"
            exit 1
        fi

        # Install certificate
        cp "/tmp/${DOMAIN}.crt" "$CERT_DIR/"
        cp "/tmp/${DOMAIN}.key" "$CERT_DIR/"

        # Set permissions
        chmod 600 "$CERT_DIR/${DOMAIN}.key"
        chmod 644 "$CERT_DIR/${DOMAIN}.crt"

        echo "Certificate installed for $DOMAIN"
        ;;

    renew)
        if [ -z "$DOMAIN" ]; then
            echo "Usage: $0 renew <domain>"
            exit 1
        fi

        # Renew with Let's Encrypt (requires certbot)
        if command -v certbot >/dev/null; then
            certbot certonly --webroot -w /var/www/html -d "$DOMAIN"

            # Copy to nginx directory
            cp "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" "$CERT_DIR/${DOMAIN}.crt"
            cp "/etc/letsencrypt/live/${DOMAIN}/privkey.pem" "$CERT_DIR/${DOMAIN}.key"

            # Set permissions
            chmod 600 "$CERT_DIR/${DOMAIN}.key"
            chmod 644 "$CERT_DIR/${DOMAIN}.crt"

            # Reload nginx
            nginx -s reload

            echo "Certificate renewed for $DOMAIN"
        else
            echo "Certbot not installed. Install with: dnf install certbot"
        fi
        ;;

    list)
        echo "=== SSL Certificates ==="
        for cert in "$CERT_DIR"/*.crt; do
            if [ -f "$cert" ]; then
                domain=$(basename "$cert" .crt)
                echo "Domain: $domain"
                openssl x509 -in "$cert" -noout -subject -dates
                echo ""
            fi
        done
        ;;

    test)
        if [ -z "$DOMAIN" ]; then
            DOMAIN=$(hostname -f)
        fi

        echo "Testing SSL certificate for $DOMAIN..."

        # Test certificate validity
        openssl x509 -in "$CERT_DIR/nginx.crt" -text -noout | grep -E "(Subject|Not After)"

        # Test SSL connection
        echo | openssl s_client -servername "$DOMAIN" -connect localhost:443 2>/dev/null | \
            openssl x509 -noout -subject -dates

        echo "SSL test completed"
        ;;

    *)
        echo "Usage: $0 {generate|install|renew|list|test} [domain]"
        echo "Examples:"
        echo "  $0 generate api.company.com"
        echo "  $0 install api.company.com"
        echo "  $0 renew api.company.com"
        echo "  $0 list"
        echo "  $0 test"
        ;;
esac
EOF

# Make SSL management script executable
sudo chmod +x /usr/local/bin/manage-proxy-ssl.sh

# Create advanced SSL configuration for different domains
sudo tee /etc/nginx/conf.d/ssl-domains.conf << 'EOF'
# Multi-domain SSL configuration

# API subdomain
server {
    listen 443 ssl http2;
    server_name api.company.local;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # API-specific settings
    client_max_body_size 10m;

    location / {
        limit_req zone=api burst=10 nodelay;

        proxy_pass http://backend_api;
        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;

        # API headers
        add_header X-API-Version "v1.0" always;
        add_header X-RateLimit-Limit "100" always;
    }
}

# Admin subdomain with IP restrictions
server {
    listen 443 ssl http2;
    server_name admin.company.local;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # Restrict access to admin networks
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;

    location / {
        proxy_pass http://backend_web;
        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;

        # Admin-specific headers
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options DENY always;
    }
}

# Static content subdomain
server {
    listen 443 ssl http2;
    server_name static.company.local;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    location / {
        proxy_pass http://backend_static;
        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;

        # Aggressive caching for static content
        proxy_cache static_cache;
        proxy_cache_valid 200 301 302 24h;
        proxy_cache_valid 404 10m;
        proxy_cache_lock on;
        proxy_cache_use_stale error timeout updating;

        expires 1y;
        add_header Cache-Control "public, immutable";
        add_header X-Cache-Status $upstream_cache_status;
    }
}
EOF

# Test SSL certificate
sudo /usr/local/bin/manage-proxy-ssl.sh test

echo "SSL/TLS termination configured successfully!"

Expected output:

Generating a RSA private key
......+++++
......+++++
writing new private key to '/etc/ssl/nginx/nginx.key'
-----
Certificate generated for proxy.company.local
Subject: C = US, ST = State, L = City, O = Company, OU = IT Department, CN = proxy.company.local
Not After : Sep 17 16:30:45 2026 GMT
SSL/TLS termination configured successfully!

Amazing! ๐ŸŒŸ SSL/TLS termination is configured with multi-domain support!

โœ… Step 4: Configure Firewall and Start Services

Set up firewall rules and start Nginx services! ๐Ÿ”ฅ

# Enable and start firewalld
sudo systemctl enable firewalld
sudo systemctl start firewalld

# Add HTTP and HTTPS services to firewall
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

# Add custom ports if needed
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --permanent --add-port=3000/tcp

# Add SSH for remote management
sudo firewall-cmd --permanent --add-service=ssh

# Reload firewall rules
sudo firewall-cmd --reload

# Verify firewall configuration
sudo firewall-cmd --list-all

# Configure SELinux for Nginx
sudo setsebool -P httpd_can_network_connect 1
sudo setsebool -P httpd_can_network_relay 1

# Check SELinux status
getsebool -a | grep httpd

# Enable and start Nginx service
sudo systemctl enable nginx
sudo systemctl start nginx

# Check service status
sudo systemctl status nginx

# Verify Nginx is listening on correct ports
sudo ss -tlnp | grep nginx

# Test reverse proxy functionality
curl -I http://localhost/
curl -k -I https://localhost/

# Check Nginx processes
ps aux | grep nginx

Expected output:

success
success
success
public (active)
  services: ssh http https
  ports: 8080/tcp 3000/tcp

httpd_can_network_connect --> on
httpd_can_network_relay --> on

โ— nginx.service - The nginx HTTP and reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled)
     Active: active (running) since Tue 2025-09-17 16:45:15 EDT

LISTEN 0 128 *:80 *:* users:(("nginx",pid=1234,fd=6))
LISTEN 0 128 *:443 *:* users:(("nginx",pid=1234,fd=7))

Perfect! ๐ŸŽ‰ Nginx reverse proxy is running and ready to handle traffic!

๐Ÿ”ง Step 5: Configure Advanced Features

Implement advanced reverse proxy features for enterprise use! ๐Ÿ“Š

# Create advanced caching configuration
sudo tee /etc/nginx/conf.d/advanced-cache.conf << 'EOF'
# Advanced Caching Configuration

# Cache zones
proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:50m inactive=60m use_temp_path=off;
proxy_cache_path /var/cache/nginx/images levels=1:2 keys_zone=image_cache:100m inactive=24h use_temp_path=off;
proxy_cache_path /var/cache/nginx/dynamic levels=1:2 keys_zone=dynamic_cache:30m inactive=10m use_temp_path=off;

# Cache bypass conditions
map $request_method $no_cache {
    default 0;
    POST 1;
    PUT 1;
    DELETE 1;
}

map $http_cache_control $no_cache_cc {
    default 0;
    "no-cache" 1;
    "no-store" 1;
    "private" 1;
}

server {
    listen 443 ssl http2;
    server_name cache.company.local;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # API caching with smart invalidation
    location /api/ {
        proxy_pass http://backend_api/;

        proxy_cache api_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 301 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_bypass $no_cache $no_cache_cc;
        proxy_no_cache $no_cache $no_cache_cc;

        # Cache control headers
        add_header X-Cache-Status $upstream_cache_status;
        add_header X-Cache-Key "$scheme$request_method$host$request_uri";

        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;
    }

    # Image caching with long expiration
    location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
        proxy_pass http://backend_static;

        proxy_cache image_cache;
        proxy_cache_valid 200 30d;
        proxy_cache_valid 404 1h;
        proxy_cache_lock on;
        proxy_cache_use_stale error timeout updating;

        expires 30d;
        add_header Cache-Control "public, immutable";
        add_header X-Cache-Status $upstream_cache_status;

        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;
    }

    # Dynamic content with short-term caching
    location / {
        proxy_pass http://backend_web;

        proxy_cache dynamic_cache;
        proxy_cache_valid 200 5m;
        proxy_cache_valid 404 30s;
        proxy_cache_bypass $arg_nocache $cookie_nocache;

        add_header X-Cache-Status $upstream_cache_status;

        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

# Create load balancing and health check configuration
sudo tee /etc/nginx/conf.d/load-balancing.conf << 'EOF'
# Advanced Load Balancing Configuration

# Health check upstream
upstream backend_health {
    zone backend_health 64k;

    server 192.168.1.101:8080 max_fails=2 fail_timeout=30s;
    server 192.168.1.102:8080 max_fails=2 fail_timeout=30s;
    server 192.168.1.103:8080 max_fails=2 fail_timeout=30s backup;

    keepalive 32;
    keepalive_requests 100;
    keepalive_timeout 60s;
}

# Geographic load balancing
geo $backend_pool {
    default backend_web;
    192.168.1.0/24 backend_web;
    10.0.0.0/8 backend_api;
}

server {
    listen 443 ssl http2;
    server_name lb.company.local;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # Health check endpoint
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    # Upstream health check
    location /upstream-health {
        proxy_pass http://backend_health/health;
        proxy_set_header Host $host;
        proxy_connect_timeout 5s;
        proxy_read_timeout 5s;
        access_log off;
    }

    # Main application with geographic routing
    location / {
        proxy_pass http://$backend_pool;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;

        # Circuit breaker
        proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;
        proxy_next_upstream_timeout 30s;
    }
}
EOF

# Create monitoring and metrics configuration
sudo tee /etc/nginx/conf.d/monitoring.conf << 'EOF'
# Monitoring and Metrics Configuration

server {
    listen 8080;
    server_name localhost;

    # Metrics endpoint (basic)
    location /nginx-status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
    }

    # Detailed metrics (if nginx-plus)
    location /api {
        api write=on;
        access_log off;
        allow 127.0.0.1;
        allow 192.168.1.0/24;
        deny all;
    }

    # Cache status
    location /cache-status {
        access_log off;
        return 200 "Cache Status: OK\n";
        add_header Content-Type text/plain;
    }
}
EOF

# Create cache management scripts
sudo tee /usr/local/bin/manage-nginx-cache.sh << 'EOF'
#!/bin/bash
# Nginx Cache Management

CACHE_DIR="/var/cache/nginx"

case "$1" in
    clear)
        echo "Clearing all Nginx caches..."
        sudo rm -rf $CACHE_DIR/*/
        sudo systemctl reload nginx
        echo "Cache cleared"
        ;;

    clear-api)
        echo "Clearing API cache..."
        sudo rm -rf $CACHE_DIR/api/
        echo "API cache cleared"
        ;;

    clear-images)
        echo "Clearing image cache..."
        sudo rm -rf $CACHE_DIR/images/
        echo "Image cache cleared"
        ;;

    status)
        echo "=== Cache Status ==="
        echo "API Cache:"
        du -sh $CACHE_DIR/api/ 2>/dev/null || echo "  No cache data"

        echo "Image Cache:"
        du -sh $CACHE_DIR/images/ 2>/dev/null || echo "  No cache data"

        echo "Static Cache:"
        du -sh $CACHE_DIR/static/ 2>/dev/null || echo "  No cache data"

        echo "Dynamic Cache:"
        du -sh $CACHE_DIR/dynamic/ 2>/dev/null || echo "  No cache data"

        echo "Total Cache Size:"
        du -sh $CACHE_DIR/ 2>/dev/null || echo "  No cache data"
        ;;

    stats)
        echo "=== Cache Statistics ==="
        curl -s http://localhost:8080/nginx-status
        ;;

    *)
        echo "Usage: $0 {clear|clear-api|clear-images|status|stats}"
        ;;
esac
EOF

# Make cache management script executable
sudo chmod +x /usr/local/bin/manage-nginx-cache.sh

# Create necessary cache directories
sudo mkdir -p /var/cache/nginx/{api,images,dynamic}
sudo chown -R nginx:nginx /var/cache/nginx/

# Test advanced configuration
sudo nginx -t

# Reload Nginx with new configuration
sudo systemctl reload nginx

echo "Advanced reverse proxy features configured!"

Expected output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Advanced reverse proxy features configured!

Excellent! โœ… Advanced features including caching, load balancing, and monitoring are configured!

๐ŸŽฎ Quick Examples

Here are practical examples of using your Nginx reverse proxy in real scenarios! ๐ŸŒŸ

Example 1: Microservices API Gateway ๐Ÿ—๏ธ

# Configure Nginx as a microservices API gateway
sudo tee /etc/nginx/conf.d/api-gateway.conf << 'EOF'
# Microservices API Gateway Configuration

# Service upstreams
upstream user_service {
    server 192.168.1.201:3001 weight=2;
    server 192.168.1.202:3001 weight=2;
    server 192.168.1.203:3001 weight=1 backup;
    keepalive 16;
}

upstream order_service {
    server 192.168.1.211:3002 weight=3;
    server 192.168.1.212:3002 weight=3;
    keepalive 16;
}

upstream payment_service {
    server 192.168.1.221:3003 weight=1;
    server 192.168.1.222:3003 weight=1;
    keepalive 8;
}

upstream notification_service {
    server 192.168.1.231:3004;
    keepalive 8;
}

# Rate limiting zones
limit_req_zone $binary_remote_addr zone=auth:10m rate=5r/s;
limit_req_zone $binary_remote_addr zone=users:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=orders:10m rate=15r/s;
limit_req_zone $binary_remote_addr zone=payments:10m rate=2r/s;

server {
    listen 443 ssl http2;
    server_name api.company.com;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # Global API settings
    client_max_body_size 10m;

    # CORS headers
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;

    # API versioning
    location ~ ^/api/v([0-9]+)/ {
        set $api_version $1;

        # Version-specific routing
        if ($api_version = "1") {
            rewrite ^/api/v1/(.*)$ /v1/$1 break;
        }
        if ($api_version = "2") {
            rewrite ^/api/v2/(.*)$ /v2/$1 break;
        }

        proxy_pass http://backend_api;
        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_set_header X-API-Version $api_version;
    }

    # Authentication service
    location /api/auth/ {
        limit_req zone=auth burst=10 nodelay;

        proxy_pass http://user_service/auth/;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;

        # No caching for auth
        proxy_cache_bypass 1;
        proxy_no_cache 1;
    }

    # User service
    location /api/users/ {
        limit_req zone=users burst=20 nodelay;

        # JWT token validation (add auth_request if available)
        # auth_request /auth;

        proxy_pass http://user_service/;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;

        # Cache user data for 5 minutes
        proxy_cache api_cache;
        proxy_cache_valid 200 5m;
        proxy_cache_key "$scheme$request_method$host$request_uri$http_authorization";
    }

    # Order service
    location /api/orders/ {
        limit_req zone=orders burst=30 nodelay;

        proxy_pass http://order_service/;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;

        # Longer timeout for complex order processing
        proxy_read_timeout 120s;
        proxy_send_timeout 120s;
    }

    # Payment service (high security)
    location /api/payments/ {
        limit_req zone=payments burst=5 nodelay;

        # Additional security headers
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options DENY always;

        proxy_pass http://payment_service/;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;

        # No caching for payments
        proxy_cache_bypass 1;
        proxy_no_cache 1;

        # Strict timeouts
        proxy_read_timeout 60s;
        proxy_send_timeout 60s;
    }

    # Notification service
    location /api/notifications/ {
        proxy_pass http://notification_service/;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        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;

        # Async processing, don't wait for response
        proxy_buffering off;
    }

    # WebSocket support for real-time features
    location /api/ws/ {
        proxy_pass http://notification_service/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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;

        # WebSocket timeouts
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
    }

    # API documentation
    location /docs/ {
        root /var/www/api-docs;
        try_files $uri $uri/ /index.html;

        expires 1h;
        add_header Cache-Control "public";
    }
}
EOF

# Create API gateway management script
sudo tee /usr/local/bin/manage-api-gateway.sh << 'EOF'
#!/bin/bash
# API Gateway Management Script

case "$1" in
    status)
        echo "=== API Gateway Status ==="
        curl -s http://localhost:8080/nginx-status

        echo -e "\n=== Service Health ==="
        services=(user_service order_service payment_service notification_service)
        for service in "${services[@]}"; do
            echo "Checking $service..."
            # Add actual health check URLs here
        done
        ;;

    reload)
        echo "Reloading API Gateway configuration..."
        sudo nginx -t && sudo systemctl reload nginx
        ;;

    metrics)
        echo "=== API Metrics ==="
        echo "Total requests: $(curl -s http://localhost:8080/nginx-status | grep requests | awk '{print $3}')"
        echo "Active connections: $(curl -s http://localhost:8080/nginx-status | grep Active | awk '{print $3}')"
        ;;

    *)
        echo "Usage: $0 {status|reload|metrics}"
        ;;
esac
EOF

sudo chmod +x /usr/local/bin/manage-api-gateway.sh

echo "Microservices API Gateway configured"

Example 2: Content Delivery Network (CDN) Setup ๐ŸŒ

# Configure Nginx as a CDN edge server
sudo tee /etc/nginx/conf.d/cdn.conf << 'EOF'
# CDN Edge Server Configuration

# Origin servers
upstream origin_images {
    server 192.168.1.101:80 weight=3;
    server 192.168.1.102:80 weight=3;
    server 192.168.1.103:80 weight=1 backup;
    keepalive 32;
}

upstream origin_videos {
    server 192.168.1.111:80 weight=2;
    server 192.168.1.112:80 weight=2;
    keepalive 16;
}

upstream origin_static {
    server 192.168.1.121:80;
    server 192.168.1.122:80;
    keepalive 16;
}

# Enhanced cache configuration
proxy_cache_path /var/cache/nginx/cdn-images levels=1:2 keys_zone=cdn_images:200m inactive=7d max_size=10g use_temp_path=off;
proxy_cache_path /var/cache/nginx/cdn-videos levels=1:2 keys_zone=cdn_videos:500m inactive=30d max_size=50g use_temp_path=off;
proxy_cache_path /var/cache/nginx/cdn-static levels=1:2 keys_zone=cdn_static:100m inactive=1d max_size=5g use_temp_path=off;

server {
    listen 443 ssl http2;
    server_name cdn.company.com;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # Global settings
    client_max_body_size 100m;

    # Image delivery with optimization
    location ~* \.(jpg|jpeg|png|gif|webp|svg|ico)$ {
        proxy_pass http://origin_images;

        # Aggressive caching
        proxy_cache cdn_images;
        proxy_cache_valid 200 301 302 30d;
        proxy_cache_valid 404 10m;
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_background_update on;

        # Cache headers
        add_header X-Cache-Status $upstream_cache_status always;
        add_header X-Cache-Date $upstream_http_date;

        # Client-side caching
        expires 30d;
        add_header Cache-Control "public, immutable";
        add_header Vary "Accept-Encoding";

        # Image optimization headers
        add_header Accept-CH "DPR, Viewport-Width, Width";

        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;

        # Range requests for large images
        proxy_set_header Range $http_range;
        proxy_set_header If-Range $http_if_range;
    }

    # Video delivery with range support
    location ~* \.(mp4|webm|ogg|avi|mov|wmv|flv|3gp)$ {
        proxy_pass http://origin_videos;

        # Video caching
        proxy_cache cdn_videos;
        proxy_cache_valid 200 206 301 302 7d;
        proxy_cache_valid 404 1h;
        proxy_cache_lock on;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;

        # Range request support
        proxy_set_header Range $http_range;
        proxy_set_header If-Range $http_if_range;

        # Headers
        add_header X-Cache-Status $upstream_cache_status always;
        add_header Accept-Ranges bytes;

        expires 7d;
        add_header Cache-Control "public";

        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;

        # Larger buffers for video
        proxy_buffering on;
        proxy_buffer_size 8k;
        proxy_buffers 32 8k;
    }

    # Static assets (CSS, JS, fonts)
    location ~* \.(css|js|woff|woff2|ttf|eot)$ {
        proxy_pass http://origin_static;

        proxy_cache cdn_static;
        proxy_cache_valid 200 301 302 1d;
        proxy_cache_valid 404 1h;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;

        # Compression
        gzip_static on;

        add_header X-Cache-Status $upstream_cache_status always;

        expires 1d;
        add_header Cache-Control "public";
        add_header Vary "Accept-Encoding";

        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;
    }

    # Cache purge endpoint (restricted access)
    location ~ /purge(/.*) {
        allow 192.168.1.0/24;
        deny all;

        proxy_cache_purge cdn_images "$scheme$request_method$host$1";
        proxy_cache_purge cdn_videos "$scheme$request_method$host$1";
        proxy_cache_purge cdn_static "$scheme$request_method$host$1";
    }

    # CDN statistics
    location /cdn-stats {
        allow 192.168.1.0/24;
        deny all;

        access_log off;
        return 200 "CDN Statistics\n";
        add_header Content-Type text/plain;
    }
}
EOF

# Create CDN management script
sudo tee /usr/local/bin/manage-cdn.sh << 'EOF'
#!/bin/bash
# CDN Management Script

CDN_CACHE="/var/cache/nginx"

case "$1" in
    stats)
        echo "=== CDN Cache Statistics ==="
        echo "Images: $(du -sh $CDN_CACHE/cdn-images/ 2>/dev/null | cut -f1)"
        echo "Videos: $(du -sh $CDN_CACHE/cdn-videos/ 2>/dev/null | cut -f1)"
        echo "Static: $(du -sh $CDN_CACHE/cdn-static/ 2>/dev/null | cut -f1)"
        echo "Total: $(du -sh $CDN_CACHE/ 2>/dev/null | cut -f1)"

        echo -e "\n=== Cache Hit Rates ==="
        # Parse access logs for cache hit rates
        tail -n 1000 /var/log/nginx/access.log | grep -o 'X-Cache-Status: [A-Z]*' | sort | uniq -c
        ;;

    purge)
        if [ -z "$2" ]; then
            echo "Usage: $0 purge <path>"
            echo "Example: $0 purge /images/logo.png"
            exit 1
        fi

        echo "Purging cache for: $2"
        curl -X PURGE "http://localhost/purge$2"
        ;;

    clear)
        echo "Clearing all CDN caches..."
        sudo rm -rf $CDN_CACHE/cdn-*
        echo "CDN cache cleared"
        ;;

    *)
        echo "Usage: $0 {stats|purge <path>|clear}"
        ;;
esac
EOF

sudo chmod +x /usr/local/bin/manage-cdn.sh

# Create CDN cache directories
sudo mkdir -p /var/cache/nginx/{cdn-images,cdn-videos,cdn-static}
sudo chown -R nginx:nginx /var/cache/nginx/

echo "CDN configuration complete"

Example 3: Web Application Firewall (WAF) Integration ๐Ÿ›ก๏ธ

# Configure Nginx with WAF capabilities
sudo tee /etc/nginx/conf.d/waf.conf << 'EOF'
# Web Application Firewall Configuration

# Security maps
map $http_user_agent $blocked_agent {
    default 0;
    ~*malicious 1;
    ~*scanner 1;
    ~*bot 1;
    ~*crawler 0;  # Allow legitimate crawlers
}

map $request_uri $blocked_uri {
    default 0;
    ~*/\.\. 1;  # Directory traversal
    ~*\.(php|asp|jsp)$ 1;  # Script execution
    ~*/admin/phpmyadmin 1;  # Admin tools
    ~*/wp-admin 1;  # WordPress admin (if not using WordPress)
}

map $args $blocked_args {
    default 0;
    ~*union.*select 1;  # SQL injection
    ~*<script 1;  # XSS
    ~*javascript: 1;  # JavaScript injection
    ~*vbscript: 1;  # VBScript injection
}

# Rate limiting zones
limit_req_zone $binary_remote_addr zone=waf_general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=waf_login:10m rate=1r/m;
limit_req_zone $binary_remote_addr zone=waf_api:10m rate=100r/m;

# Connection limiting
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    listen 443 ssl http2;
    server_name secure.company.com;

    ssl_certificate /etc/ssl/nginx/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx/nginx.key;

    # WAF rules
    if ($blocked_agent) {
        return 444;  # Drop connection
    }

    if ($blocked_uri) {
        return 403;
    }

    if ($blocked_args) {
        return 403;
    }

    # Connection limits
    limit_conn addr 10;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # Login protection
    location /login {
        limit_req zone=waf_login burst=5 nodelay;

        # Additional login security
        if ($request_method !~ ^(GET|POST)$) {
            return 405;
        }

        proxy_pass http://backend_web;
        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;

        # No caching for login
        proxy_cache_bypass 1;
        proxy_no_cache 1;
    }

    # API endpoints with protection
    location /api/ {
        limit_req zone=waf_api burst=200 nodelay;

        # Content length limit
        client_max_body_size 1m;

        # Request method filtering
        if ($request_method !~ ^(GET|POST|PUT|DELETE|HEAD|OPTIONS)$) {
            return 405;
        }

        proxy_pass http://backend_api/;
        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;
    }

    # File upload protection
    location /upload {
        limit_req zone=waf_general burst=10 nodelay;

        # File size limits
        client_max_body_size 10m;

        # File type restrictions
        location ~* \.(php|phtml|php3|php4|php5|pl|py|jsp|asp|sh|cgi)$ {
            return 403;
        }

        proxy_pass http://backend_web;
        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;
    }

    # Main application
    location / {
        limit_req zone=waf_general burst=20 nodelay;

        proxy_pass http://backend_web;
        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;
    }

    # Block common attack patterns
    location ~* \.(git|svn|hg)/ {
        return 404;
    }

    location ~* \.(ini|conf|config|log)$ {
        return 404;
    }
}
EOF

echo "WAF configuration complete"

๐Ÿšจ Fix Common Problems

Here are solutions to common Nginx reverse proxy issues you might encounter! ๐Ÿ”ง

Problem 1: Backend Connection Failures โŒ

# Check backend server connectivity
for backend in 192.168.1.101 192.168.1.102 192.168.1.103; do
    echo "Testing backend $backend..."
    curl -I http://$backend:8080/ || echo "Backend $backend is not responding"
done

# Check Nginx upstream configuration
grep -A 10 "upstream" /etc/nginx/nginx.conf

# Test upstream health
curl http://localhost:8080/nginx-status

# Check proxy_pass directives
grep -r "proxy_pass" /etc/nginx/conf.d/

# Debug proxy connections
sudo nginx -T | grep -E "(upstream|proxy_pass)"

# Enable debug logging temporarily
sudo tee /etc/nginx/conf.d/debug.conf << 'EOF'
error_log /var/log/nginx/debug.log debug;

server {
    listen 8888;
    location / {
        proxy_pass http://backend_web;
        proxy_set_header Host $host;
        access_log /var/log/nginx/debug_access.log;
    }
}
EOF

sudo systemctl reload nginx

# Test with debug server
curl http://localhost:8888/

# Check debug logs
sudo tail -f /var/log/nginx/debug.log

# Fix common backend issues
echo "Common fixes:"
echo "1. Check backend servers are running"
echo "2. Verify firewall allows connections"
echo "3. Check SELinux: setsebool -P httpd_can_network_connect 1"
echo "4. Verify upstream IP addresses and ports"

echo "โœ… Backend connection issues diagnosed!"

Problem 2: SSL/TLS Certificate Problems โŒ

# Test SSL certificate validity
sudo /usr/local/bin/manage-proxy-ssl.sh test

# Check SSL configuration
sudo nginx -T | grep -A 20 ssl

# Test SSL handshake
openssl s_client -connect localhost:443 -servername $(hostname -f) < /dev/null

# Check certificate files
ls -la /etc/ssl/nginx/
sudo openssl x509 -in /etc/ssl/nginx/nginx.crt -text -noout | grep -E "(Subject|Not After)"

# Verify certificate chain
openssl verify /etc/ssl/nginx/nginx.crt

# Test different SSL protocols
openssl s_client -connect localhost:443 -tls1_2 < /dev/null
openssl s_client -connect localhost:443 -tls1_3 < /dev/null

# Check for mixed content issues
curl -k -H "Host: api.company.local" https://localhost/api/health

# Generate new certificate if needed
sudo /usr/local/bin/manage-proxy-ssl.sh generate $(hostname -f)

# Test with new certificate
curl -k -I https://localhost/

echo "โœ… SSL certificate issues resolved!"

Problem 3: Caching Not Working Properly โŒ

# Check cache status
sudo /usr/local/bin/manage-nginx-cache.sh status

# Test cache headers
curl -I http://localhost/static/test.css
curl -I https://localhost/api/test

# Check cache configuration
grep -A 10 "proxy_cache" /etc/nginx/conf.d/

# Verify cache directories exist and have correct permissions
ls -la /var/cache/nginx/
sudo chown -R nginx:nginx /var/cache/nginx/

# Clear cache and test
sudo /usr/local/bin/manage-nginx-cache.sh clear

# Test cache functionality
echo "Testing cache..."
time curl -s http://localhost/static/large-file.jpg > /dev/null
time curl -s http://localhost/static/large-file.jpg > /dev/null

# Check cache hit/miss ratios
tail -n 100 /var/log/nginx/access.log | grep -o 'X-Cache-Status: [A-Z]*' | sort | uniq -c

# Enable cache debugging
sudo tee -a /etc/nginx/conf.d/cache-debug.conf << 'EOF'
location /debug-cache/ {
    proxy_pass http://backend_static/;
    proxy_cache static_cache;
    proxy_cache_valid 200 1m;

    add_header X-Cache-Status $upstream_cache_status always;
    add_header X-Cache-Key "$scheme$request_method$host$request_uri" always;
    add_header X-Cache-Debug "Cache-Path: /var/cache/nginx/static" always;
}
EOF

sudo systemctl reload nginx

echo "โœ… Caching issues resolved!"

Problem 4: High CPU and Memory Usage โŒ

# Monitor Nginx performance
top -p $(pgrep nginx)
ps aux | grep nginx

# Check worker process configuration
grep worker_processes /etc/nginx/nginx.conf

# Monitor connections
watch -n 1 'ss -s'

# Check for memory leaks
sudo valgrind nginx -t

# Optimize worker configuration
sudo tee -a /etc/nginx/nginx.conf << 'EOF'
# Performance optimizations
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}
EOF

# Optimize buffer sizes
sudo tee -a /etc/nginx/conf.d/performance.conf << 'EOF'
# Buffer optimizations
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
output_buffers 1 32k;
postpone_output 1460;

# Timeouts
client_header_timeout 30s;
client_body_timeout 30s;
keepalive_timeout 30s;
send_timeout 30s;

# File operations
sendfile on;
tcp_nopush on;
tcp_nodelay on;
EOF

# Check for excessive logging
du -sh /var/log/nginx/

# Rotate logs if needed
sudo logrotate -f /etc/logrotate.d/nginx

# Monitor after optimizations
sudo systemctl reload nginx
htop -p $(pgrep nginx)

echo "โœ… Performance optimizations applied!"

๐Ÿ“‹ Simple Commands Summary

Hereโ€™s a quick reference for essential Nginx reverse proxy management commands! ๐Ÿ“š

Command CategoryCommandDescription
Service Managementsudo systemctl start nginxStart Nginx service
sudo systemctl stop nginxStop Nginx service
sudo systemctl restart nginxRestart Nginx service
sudo systemctl reload nginxReload configuration
Configurationnginx -tTest configuration syntax
nginx -TTest and dump configuration
sudo nano /etc/nginx/nginx.confEdit main configuration
sudo nano /etc/nginx/conf.d/site.confEdit site configuration
SSL Management/usr/local/bin/manage-proxy-ssl.sh listList SSL certificates
/usr/local/bin/manage-proxy-ssl.sh generate domain.comGenerate certificate
openssl s_client -connect localhost:443Test SSL connection
Cache Management/usr/local/bin/manage-nginx-cache.sh statusCheck cache status
/usr/local/bin/manage-nginx-cache.sh clearClear all cache
/usr/local/bin/manage-nginx-cache.sh clear-apiClear API cache
Monitoringcurl http://localhost:8080/nginx-statusView basic statistics
tail -f /var/log/nginx/access.logMonitor access logs
tail -f /var/log/nginx/error.logMonitor error logs
Backend Testingcurl -I http://backend-server:8080/Test backend connectivity
telnet backend-server 8080Test TCP connection
Load Testingab -n 1000 -c 10 http://localhost/Apache Bench load test
curl -w "@curl-format.txt" http://localhost/Detailed timing info

๐Ÿ’ก Tips for Success

Here are expert tips to make your Nginx reverse proxy even better! ๐ŸŒŸ

Performance Optimization โšก

  • ๐ŸŽฏ Worker tuning: Set worker_processes to match CPU cores
  • ๐Ÿ“Š Connection limits: Optimize worker_connections based on memory
  • ๐Ÿ”„ Keep-alive: Use HTTP keep-alive to reduce connection overhead
  • ๐Ÿ’พ Buffer optimization: Tune proxy buffers for your content size
  • ๐ŸŒ Compression: Enable gzip compression for text content

Security Best Practices ๐Ÿ›ก๏ธ

  • ๐Ÿ” SSL configuration: Use strong ciphers and disable weak protocols
  • ๐Ÿšซ Rate limiting: Implement rate limiting to prevent abuse
  • ๐Ÿ“ Security headers: Add comprehensive security headers
  • ๐Ÿ” WAF rules: Implement web application firewall rules
  • ๐ŸŽ›๏ธ Access control: Use IP allowlists for sensitive endpoints

Caching Excellence ๐Ÿ’พ

  • ๐ŸŽฏ Cache zones: Configure appropriate cache zones for different content
  • ๐Ÿ“Š Cache keys: Use smart cache keys to avoid cache pollution
  • ๐Ÿ”„ Cache invalidation: Implement proper cache purging mechanisms
  • ๐Ÿ’ฝ Storage planning: Plan cache storage based on content volume
  • ๐Ÿ“ˆ Hit rate monitoring: Monitor and optimize cache hit rates

Operational Excellence ๐Ÿข

  • ๐Ÿ“š Configuration management: Use version control for configurations
  • ๐ŸŽ›๏ธ Monitoring: Implement comprehensive monitoring and alerting
  • ๐Ÿ‘ฅ Documentation: Maintain clear documentation of proxy rules
  • ๐Ÿ“Š Capacity planning: Monitor usage and plan for growth
  • ๐Ÿ”ง Automation: Automate configuration deployment and updates

๐Ÿ† What You Learned

Congratulations! Youโ€™ve successfully mastered AlmaLinux Nginx reverse proxy configuration! Hereโ€™s everything youโ€™ve accomplished: ๐ŸŽ‰

โœ… Reverse Proxy Setup: Installed and configured enterprise-grade Nginx reverse proxy โœ… SSL Termination: Implemented secure HTTPS with certificate management โœ… Load Balancing: Set up intelligent traffic distribution across backend servers โœ… Advanced Caching: Configured multi-tier caching for optimal performance โœ… API Gateway: Created microservices API gateway with routing and security โœ… CDN Capabilities: Built content delivery network functionality โœ… WAF Integration: Implemented web application firewall protection โœ… Monitoring Tools: Set up comprehensive monitoring and metrics โœ… Performance Tuning: Optimized for high-traffic applications โœ… Troubleshooting Skills: Learned to diagnose and fix proxy issues

๐ŸŽฏ Why This Matters

Building robust reverse proxy infrastructure is fundamental to modern web architecture! ๐ŸŒ Hereโ€™s the real-world impact of what youโ€™ve accomplished:

For Application Architecture: Your Nginx reverse proxy enables microservices architecture, API gateways, and modern application patterns that scale horizontally and provide better security isolation. ๐Ÿ—๏ธ

For Performance: By implementing caching, compression, and intelligent routing, youโ€™ve dramatically improved application performance and reduced backend server load. โšก

For Security: SSL termination, WAF capabilities, and centralized security controls provide enterprise-grade protection for all your applications behind the proxy. ๐Ÿ›ก๏ธ

For Scalability: Your reverse proxy setup enables seamless scaling, zero-downtime deployments, and efficient resource utilization across your entire infrastructure. ๐Ÿ“ˆ

Your AlmaLinux Nginx reverse proxy is now providing the intelligent gateway that powers modern web applications with high performance, security, and scalability! Youโ€™re not just proxying requests โ€“ youโ€™re operating the critical infrastructure layer that enables modern application architecture! โญ

Continue exploring advanced Nginx features like service mesh integration, advanced load balancing algorithms, and cloud-native reverse proxy patterns. The reverse proxy expertise youโ€™ve developed is essential for modern infrastructure! ๐Ÿ™Œ