Skip to content

28. Web Servers & Reverse Proxy

Web servers and reverse proxies form the entry point of modern infrastructure. An origin web server executes application logic and serves static assets, while a reverse proxy sits in front to terminate TLS encryption, distribute traffic across application replicas, enforce security policies, and prevent single-point bottlenecks.

28.1 Web Server vs Reverse Proxy vs Forward Proxy

Section titled “28.1 Web Server vs Reverse Proxy vs Forward Proxy”

Understanding the direction of network traffic and the role of each component is essential for infrastructure architecture:

Forward Proxy (Protects/Proxies Clients):
Internal Clients (Users) ──► Forward Proxy (e.g. Squid) ──► Internet Web Servers
Reverse Proxy (Protects/Proxies Servers):
Internet Clients (Users) ──► Reverse Proxy (e.g. Nginx) ──► Internal Application Backends
Origin Web Server (Serves Content / Logic):
Reverse Proxy (Nginx) ──► Web Server (Apache httpd) ──► PHP-FPM / Local Storage
  • Origin Web Server (e.g., Apache HTTP Server, Nginx standalone): Accepts HTTP requests, parses configuration directives, reads files from disk (/var/www/html), runs application runtimes (PHP, Python WSGI, CGI), and returns HTTP responses.
  • Reverse Proxy (e.g., Nginx, HAProxy, Envoy, Traefik): Sits in front of origin servers or microservice backends. Clients connect to the proxy, which routes requests to backend servers, shields private IP topology, caches responses, and offloads TLS processing.
  • Forward Proxy (e.g., Squid): Sits on the client side. Intercepts outbound user requests to enforce corporate egress filtering, scan for malware, or cache remote web pages.

Apache (httpd / apache2) remains one of the most widely deployed open-source web servers, featuring modular architecture (mod_rewrite, mod_ssl, mod_proxy) and robust .htaccess support.

In Red Hat ecosystems, Apache is packaged as httpd.

Terminal window
# Install Apache and SSL module
sudo dnf install httpd mod_ssl -y
# Enable and start the service
sudo systemctl enable --now httpd
sudo systemctl status httpd
Terminal window
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

RHEL enforces strict SELinux labels on web directory contents. The default document root /var/www/html/ carries the label httpd_sys_content_t.

If you host sites in custom directories (e.g., /srv/www or /var/www/app), you must set the correct SELinux context:

Terminal window
# Register persistent SELinux context for the custom path
sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/custom(/.*)?"
# Apply the context recursively
sudo restorecon -Rv /var/www/custom
# If Apache must initiate outbound network connections (reverse proxying or database sockets)
sudo setsebool -P httpd_can_network_connect 1

4. Virtual Host Configuration (/etc/httpd/conf.d/app.example.com.conf)

Section titled “4. Virtual Host Configuration (/etc/httpd/conf.d/app.example.com.conf)”
<VirtualHost *:80>
ServerName app.example.com
ServerAlias www.app.example.com
DocumentRoot /var/www/html/app
ErrorLog /var/log/httpd/app_error.log
CustomLog /var/log/httpd/app_access.log combined
<Directory /var/www/html/app>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

In Debian and Ubuntu ecosystems, Apache is packaged as apache2 and uses utility scripts (a2ensite, a2enmod) to manage configurations.

Terminal window
sudo apt update
sudo apt install apache2 -y
sudo systemctl enable --now apache2
sudo systemctl status apache2
Terminal window
sudo ufw allow 'Apache Full'
sudo ufw status

3. Directory Layout and Management Utilities

Section titled “3. Directory Layout and Management Utilities”
  • Configuration files: Stored in /etc/apache2/sites-available/
  • Active sites: Symlinked into /etc/apache2/sites-enabled/
  • Site management:
    Terminal window
    # Enable or disable a virtual host
    sudo a2ensite app.example.com.conf
    sudo a2dissite 000-default.conf
    # Enable required Apache modules
    sudo a2enmod rewrite ssl headers proxy proxy_http
    # Validate configuration syntax
    sudo apache2ctl configtest
    # Gracefully reload
    sudo systemctl reload apache2

4. Virtual Host & TLS Configuration with Let’s Encrypt

Section titled “4. Virtual Host & TLS Configuration with Let’s Encrypt”
Terminal window
# Install Certbot for Apache
sudo apt install certbot python3-certbot-apache -y
# Obtain and install SSL certificates automatically
sudo certbot --apache -d app.example.com -d www.app.example.com

Certbot automatically configures the SSL virtual host block (/etc/apache2/sites-available/app.example.com-le-ssl.conf) with modern TLS parameters and sets up automated renewal timers via certbot.timer.

Deploying Nginx as an edge reverse proxy in front of backend microservices or Apache web servers provides high throughput, low memory footprint (event-driven asynchronous worker model), and seamless TLS termination:

Internet / Clients
│ (HTTPS :443)
┌────────────────┐
│ Nginx Ingress │ <-- TLS Termination, Rate Limiting, Caching
└───────┬────────┘
│ (Internal HTTP / Unix Socket)
┌────────────┼────────────┐
│ │ │
┌────────────┐┌────────────┐┌────────────┐
│ App Node 1 ││ App Node 2 ││ App Node 3 │
│ (:3001) ││ (:3002) ││ (:3003) │
└────────────┘└────────────┘└────────────┘
  1. Single Entry Point: External clients connect to one public IP and domain, regardless of how many microservices run internally.
  2. TLS / SSL Termination: The reverse proxy decrypts incoming HTTPS traffic, offloading cryptographic CPU overhead from backend apps.
  3. High Availability: If App Node 2 crashes, the reverse proxy detects the failure and routes all traffic to App Node 1 and App Node 3.
  4. Security Isolation: Shields backend server topology, private IP addresses, and runtime framework headers.

28.4 Basic Nginx Reverse Proxy Configuration

Section titled “28.4 Basic Nginx Reverse Proxy Configuration”

A minimal configuration to forward public traffic on port 80 to a local Node.js, Go, or Python backend running on port 3000:

server {
listen 80;
server_name api.example.com;
location / {
# Forward the request to the internal backend
proxy_pass http://127.0.0.1:3000;
# Preserve client headers (CRITICAL for logging & security)
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;
# WebSockets support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}

[!IMPORTANT] If you do not pass X-Real-IP and X-Forwarded-For, your backend application logs will show 127.0.0.1 as the source IP for every user on the internet!

To distribute traffic across multiple application instances, use the upstream block in Nginx:

# Define the pool of backend application servers
upstream backend_cluster {
server 10.0.0.11:3000 weight=3; # Handles 3x more traffic
server 10.0.0.12:3000;
server 10.0.0.13:3000 backup; # Only receives traffic if primary nodes fail
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend_cluster;
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;
}
}

Nginx supports several load distribution algorithms:

Requests are distributed evenly in sequential rotation across all upstream servers:

upstream backend {
server app1.internal:8080;
server app2.internal:8080;
}

Directs more requests to servers with higher capacity using the weight parameter:

upstream backend {
server app1.internal:8080 weight=2; # Receives 2 out of every 3 requests
server app2.internal:8080 weight=1;
}

Sends new requests to the server with the fewest active open connections. Ideal for long-running transactions (file uploads, heavy database queries):

upstream backend {
least_conn;
server app1.internal:8080;
server app2.internal:8080;
}

Computes a hash of the client’s IPv4 address to consistently route that client to the same backend server (Session Persistence / Sticky Sessions):

upstream backend {
ip_hash;
server app1.internal:8080;
server app2.internal:8080;
}

Nginx open-source handles passive health checks automatically via max_fails and fail_timeout:

upstream backend {
# If a server fails 3 times in 10 seconds, mark it inactive for 30 seconds
server 10.0.0.11:3000 max_fails=3 fail_timeout=30s;
server 10.0.0.12:3000 max_fails=3 fail_timeout=30s;
server 10.0.0.13:3000 max_fails=3 fail_timeout=30s;
}

Prevent slow or unresponsive backends from holding connections open:

location / {
proxy_pass http://backend;
# Timeouts for connecting and reading from upstream
proxy_connect_timeout 3s;
proxy_read_timeout 10s;
proxy_send_timeout 10s;
# Immediately retry next server if current node returns 502/503/504
proxy_next_upstream error timeout invalid_header http_502 http_503 http_504;
}

28.7 TLS / SSL Termination & Security Headers

Section titled “28.7 TLS / SSL Termination & Security Headers”

Terminating TLS at Nginx centralizes certificate management, allowing you to renew certificates in one place (e.g., with Let’s Encrypt / Certbot) while backend apps communicate in fast, unencrypted HTTP over a private VPC network:

server {
listen 80;
server_name example.com www.example.com;
# Redirect all HTTP requests to HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL Certificates
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Modern SSL Protocols & Ciphers
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
# Enterprise Security Headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header X-XSS-Protection "1; mode=block";
location / {
proxy_pass http://backend_cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
}
}

Never reload a web server or reverse proxy in production without verifying syntax:

Terminal window
# Test Nginx syntax
sudo nginx -t
# Gracefully reload Nginx without dropping active client connections
sudo systemctl reload nginx
# Test Apache syntax
sudo apachectl configtest # RHEL (httpd)
sudo apache2ctl configtest # Ubuntu (apache2)
# Gracefully reload Apache
sudo systemctl reload httpd # RHEL
sudo systemctl reload apache2 # Ubuntu

Common HTTP Proxy Status Codes & Diagnostics

Section titled “Common HTTP Proxy Status Codes & Diagnostics”
  • 502 Bad Gateway: Nginx received an invalid response or connection reset from the upstream application (backend service is down, crashing on start, or not listening on specified port).
  • 504 Gateway Timeout: Upstream application took longer to respond than proxy_read_timeout (database slow query, external API bottleneck, application deadlock).
  • 500 Internal Server Error: Origin application generated an unhandled exception or Nginx internal file permission error.